【问题标题】:Content script answer twice on popup message - Chrome Extensions内容脚本在弹出消息上回答两次 - Chrome 扩展
【发布时间】:2014-07-03 16:47:43
【问题描述】:

我得到了结果,但它返回两个警报“内容:这是一个测试”,但在脚本中我只发送了 1 个帖子。 它工作完美,但两个答案太烦人了。请帮忙。

清单:

 {
"name": "Test",
"version": "1.0",
"manifest_version": 2,
"description": "Test",
"background": {
    "scripts": ["event.js"],
    "persistent": true
 }, 
"content_security_policy": "script-src 'self' 'unsafe-eval';  object-src 'self'",
"permissions": [ "tabs", "http://*/*", "https://*/*" ],
"content_scripts": [
    {
        "matches": ["http://*/*", "https://*/*"],
             "js": ["content.js"],
         "run_at": "document_end",
     "all_frames": true
    }
], 
"browser_action": {
            "name": "Do Action",
    "default_icon": "icon.png",
    "default_popup": "popup.html"
}}

弹出 script.js:

    $("#myButton").click(function(){    


             chrome.tabs.getSelected(null, function(tab) 
             {      
                      chrome.tabs.executeScript(tab.id, { file: "content.js" }, function() 
                      {
                              var port = chrome.tabs.connect(tab.id, { name: "port-conn" });
                              port.postMessage({ data: "This is a test" });
                              port.onMessage.addListener(function (msg) 
                              {
                                    alert("Content: " + msg.answer);
                              });
                     });
             });
  }...

content.js:

chrome.extension.onConnect.addListener(function(port) { 
port.onMessage.addListener(function(msg) { 
    port.postMessage({answer: msg.data});
}); 

});

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension background


    【解决方案1】:

    Content.js 首先在清单中指定,因此它现在在加载扩展程序时加载。然后你通过executeScript 使用它,所以它第二次运行。 做这些改变。

    弹出脚本.js:

        chrome.tabs.getSelected(null, function(tab){                                      
        var port = chrome.tabs.connect(tab.id, { name: "port-conn" });
        port.onMessage.addListener(function (msg) 
             {
                 alert("Content: " + msg.answer);
             });
        $("#myButton").click(function(){    
             port.postMessage({ data: "This is a test" });
        });
    });
    

    这就是消息传递的重点。如果它不起作用,那么你必须使用BACKGROUND 脚本以及在content 和popup 之间转发消息

    【讨论】:

    • 另请注意:"all_frames": true 将导致与文档中的框架一样多的插入,并可能导致类似的症状。
    【解决方案2】:

    问题解决了。

    在清单中

    "content_scripts": [
    {
        "matches": ["http://*/*", "https://*/*"],
             "js": ["content.js"],
         "run_at": "document_end",
     "all_frames": true
    }
    

    ],

    它在每个页面上运行 content.js 并且

    { file: "content.js" }
    

    在活动选项卡中再次运行它。所以这就是为什么一个标签会运行两次内容。

    【讨论】:

      猜你喜欢
      • 2017-12-24
      • 2011-08-31
      • 2019-11-05
      • 2013-10-12
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多