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

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

在按下它们时对background.js键进行绑定:从background.js -> contentScript.js发送消息background.js -> contentScript.jscontentScript.js -> background.js发送响应contentScript.js -> background.js

这是menifit.json定义:

  "background" : { "scripts" : ["background.js"], "persistent" : true }, "content_scripts": [ { "matches": ["*://*/*"], "js": ["contentScript.js"] } ], 

绑定部分工作正常。

这是background.js的代码:

  chrome.runtime.sendMessage({greeting: "hello"}, function(response) { console.log(response.farewell); }); }); 

以下是contentScript.js的代码:

 chrome.runtime.onMessage.addListener(HandleMessage); function HandleMessage(request, sender, sendResponse) { if (request.greeting == "hello") { sendResponse({farewell: "goodbye"}); } }; 

这是我得到的错误:

 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) 

如有变化

 console.log(response.farewell); 

 console.log("OK"); 

它工作正常,但这样我无法从contentScript.js获取值

我应该改变什么?

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

 chrome.runtime.sendMessage({greeting: "hello"}, function(response) { console.log(response.farewell); }); 

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

 Error in event handler for (unknown): Cannot read property 'farewell' of undefined Stack trace: TypeError: Cannot read property 'farewell' of undefined 

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

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

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

在Chrome扩展程序中有3种发送消息的方式,您可以参考消息传递 。

通常使用一次性请求,例如:

在background.js中

 chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {message: "hello"}, function(response) { console.log(response); }); }); 

在contentscripts.js中

 chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { console.log(request.message); if (request.message == "hello") { sendResponse({farewell: "goodbye"}); } });