代码之家  ›  专栏  ›  技术社区  ›  Vikram Deshmukh Nicolas Payette

在Chrome扩展中使用Chrome文本语音

  •  3
  • Vikram Deshmukh Nicolas Payette  · 技术社区  · 11 年前

    现在,这里有一个 demo of a chrome app 它使用chrome文本到语音引擎。

    here's the source 我已将此应用程序修改为作为“扩展”而不是应用程序。 但是,tts似乎不可用。 我已在我的“权限”下添加了“tts” 清单文件 .

    {
      "manifest_version": 2,
      "name": "Text2Speech",
      "version": "1",
      "minimum_chrome_version": "23",
      "icons": {
        "16": "icon_16.png",
        "128": "icon_128.png"
      },
      "permissions": ["tts"],
      "content_scripts": [
        {
          "matches": ["http://*/*"],
          "js": ["js/jquery-1.7.2.min.js", "js/app.js"]
        }
      ]
    }
    

    这是我迄今为止的代码:

    $(document).ready(function(){
      $(document).on("keypress", function(e) { 
        if ( e.shiftKey && ( e.keyCode === 108 || e.keyCode === 76) ) {
          console.log( "You pressed SHIFT + L" , $(prevElement).text());
          saySomething($(prevElement).text());
        }
      });
    });
    var prevElement = null;
    document.addEventListener('mousemove',
      function(e){
          var elem = e.target || e.srcElement;
          if (prevElement!= null) {prevElement.classList.remove("mouseOn");}
          elem.classList.add("mouseOn");
          prevElement = elem;
      },true);
    
    function saySomething(toSay) {
      chrome.tts.speak(toSay, { rate: 0.8, onEvent: function(event) {}}, function(evt) {});
    }
    

    我收到一个错误 saySomething 方法

    Uncaught TypeError: Cannot read property 'speak' of undefined

    感谢任何帮助。

    2 回复  |  直到 11 年前
        1
  •  4
  •   François Beaufort    11 年前

    根据 https://developer.chrome.com/extensions/content_scripts ,内容脚本有一些限制。他们 不能 :

    使用chrome.*API,以下情况除外:

    • 扩展名(getURL,inIncognitoContext,lastError,onRequest,sendRequest)
    • 18亿
    • 运行时(connect,getManifest,getURL,id,onConnect,onMessage,sendMessage)
    • 存储

    您可能希望将内容脚本中的消息发送到后台页面,如 https://developer.chrome.com/extensions/messaging#simple

    // content script
    chrome.runtime.sendMessage({toSay: "hello Vikram"}, function() {});
    
    // background page
    chrome.runtime.onMessage.addListener(function(request) {
      chrome.tts.speak(request.toSay, 
                      { rate: 0.8, onEvent: function(event) {}}, function() {});
    });
    
        2
  •  2
  •   James    11 年前

    我认为你必须在后台页面而不是在内容脚本中使用chrome.tts。

    请参见以下示例: https://developer.chrome.com/extensions/samples#speak-selection