0

我基本上是在尝试执行 Chrome 扩展文档中的代码。这就是我卡住的地方。

我正在尝试从内容脚本>>背景页面(对于XHR)传递值。

我进入控制台的错误是:

端口错误:无法建立连接。接收端不存在。miscellaneous_bindings:236

“未定义”的事件处理程序错误:无法读取未定义的属性“告别” 类型错误:无法
在 chrome-extension://bccajmddlghglocgmkpkpbiankmhlfkc/js/content_script.js:23:23
在 miscellaneous_bindings读取未定义的属性“告别” :281:11
at chrome.Event.dispatchToListener (event_bindings:387:21)
at chrome.Event.dispatch_ (event_bindings:373:27)
at chrome.Event.dispatch (event_bindings:393:17)
at Object.chromeHidden.Port。 dispatchOnDisconnect (miscellaneous_bindings:239:27)

content_script.js看起来像这样:

function func1(){

$(function() {

    $('.genericStreamStory').each(function(){
       var link = $(this).find('.uiStreamSource a').attr('href');

       $(this).find('.uiStreamFooter').find('.a1').remove();
       $(this).find('.uiStreamFooter').append("<span class='a1' style='color:red !important;'> · Sample</span>");


       $(this).find('.a1').click(function(){
           alert('hi');
            chrome.extension.sendMessage({greeting: "hello"}, function(response) {
              console.log(response.farewell);
        });

        console.log('testing');

       }); //end of click handler
    });     //end of 'each' function
});

}
func1();
window.setInterval("func1()", 1000);

发送消息语句chrome.extension.sendMessage({greeting: "hello"}, function(response) { console.log(response.farewell); });

取自Chrome 扩展文档

背景.js

$(function() {

    chrome.extension.onMessage.addListener(
        function(request, sender, sendResponse) {
          console.log("background");
          console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
          if (request.greeting == "hello")
          sendResponse({farewell: "goodbye"});
 });// end of onMessage listener

});

onMessage Listener 的代码取自 Chrome 文档。

最后,manifest.json

{
"name": "Facebook123",
"version": "0.1", 
"description": "Sample",

"content_scripts": [
    {
        "matches": ["https://*.facebook.com/*"],
        "js": [
                "/js/external/jquery.js", 
                "/js/content_script.js"
            ]
    }
],

"background": {
    "scripts": ["/js/background.js"]
},

"manifest_version": 2
}

看起来侦听器似乎无法“处理” conrent_script.js 发送的消息。

content_script.js 中的 Click 处理程序正在工作。当我单击跨度“a1”时,会弹出“hi”警报框,并在控制台中打印“testing”消息。

可能是什么错误?

4

1 回答 1

1

打开后台页面的控制台(Where to read console messages from background.js in a Chrome extension?)。

您会看到类似“ReferenceError: $ is not defined”的错误,因为您在使用$(function() { });时没有加载 jQuery。
您不必等待后台页面中的 domready 事件,因此删除$(function(){});解决问题。另一种解决方法是包含 jQuery:

"background": {
    "scripts": [
        "/js/external/jquery.js", 
        "/js/background.js"
    ]
},

通常,“端口错误”表示您正在尝试发送消息,而没有人在收听消息。在这种情况下,监听器没有因为错误而被绑定,但你经常会发现序列(事件绑定、事件触发)的时机不对,需要修复。

于 2013-03-20T11:18:58.770 回答