在'background.js'到'contentScript.js'之间传递简单信息

USe*_*299 4 javascript jquery google-chrome google-chrome-extension

我正在尝试应用以下流程:

background.js按下时键中的键的绑定:从background.js -> contentScript.js 发送响应发送消息contentScript.js -> background.js

这是menifit.json定义:

  "background" : {

    "scripts" : ["background.js"],
    "persistent" : true
    },
  "content_scripts": [
    {
      "matches": ["*://*/*"],      
      "js": ["contentScript.js"]
    }
    ],
Run Code Online (Sandbox Code Playgroud)

绑定部分工作正常.

这是以下代码background.js:

    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
        console.log(response.farewell);
        });
    });
Run Code Online (Sandbox Code Playgroud)

这是以下代码contentScript.js:

chrome.runtime.onMessage.addListener(HandleMessage);

function HandleMessage(request, sender, sendResponse)
{
    if (request.greeting == "hello")
    {
        sendResponse({farewell: "goodbye"});        
    }
};
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

Error in event handler for (unknown): Cannot read property 'farewell' of undefined
Stack trace: TypeError: Cannot read property 'farewell' of undefined
    at chrome-extension://fejkdlpdejnjkmaeadiclinbijnjoeei/background.js:64:26
    at disconnectListener (extensions::messaging:338:9)
    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
    at EventImpl.dispatchToListener (extensions::event_bindings:397:22)
    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
    at Event.publicClass.(anonymous function) [as dispatchToListener] (extensions::utils:93:26)
    at EventImpl.dispatch_ (extensions::event_bindings:379:35)
    at EventImpl.dispatch (extensions::event_bindings:403:17)
    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
    at Event.publicClass.(anonymous function) [as dispatch] (extensions::utils:93:26) 
Run Code Online (Sandbox Code Playgroud)

如有变化

console.log(response.farewell);
Run Code Online (Sandbox Code Playgroud)

console.log("OK");
Run Code Online (Sandbox Code Playgroud)

它工作正常,但这样我无法从中得到价值 contentScript.js

我应该改变什么?

Viv*_*han 6

您正尝试将消息从后台页面发送到内容脚本.从官方文档中,您使用此代码段从后台页面发送消息:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
 console.log(response.farewell);
});
Run Code Online (Sandbox Code Playgroud)

但是,文档清楚地提到上面提到的代码是内容脚本发送消息.这就是为什么你可能会收到错误的原因:

Error in event handler for (unknown): Cannot read property 'farewell' of undefined
Stack trace: TypeError: Cannot read property 'farewell' of undefined
Run Code Online (Sandbox Code Playgroud)

您想要实现的是从扩展(后台页面)向内容脚本发送请求,该内容脚本要求您指定内容脚本所在的选项卡:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
     console.log(response.farewell);
  });
});
Run Code Online (Sandbox Code Playgroud)

我希望这能澄清事情,让你开始朝着正确的方向前进.

  • 内容脚本在打开选项卡的网页上运行.这只是指定您要将消息发送到哪个选项卡. (2认同)
  • 好的,现在正在运作.问题是网页已经打开,不得不关闭它并重新打开它. (2认同)