问题描述
我是Chrome扩展程序的新手。我试图在内容脚本和 background.html 页面之间进行通信。 background.html 向内容脚本发送一个请求 hello ,内容脚本应该以 hello background 提醒作为回应。但这只是没有发生。我的 background.html 代码是:
I am new to Chrome extensions. I am trying to communicate between the content script and the background.html page. The background.html sends a request, "hello", to the content script and the content script should respond back with "hello background" alert. But it's just not happening. My background.html code is:
function testRequest() { chrome.tabs.getSelected(null, function(tab) { chrome.tabs.sendRequest(tab.id, {greeting: "hello"}); }); }
content.js code:
chrome.extension.onMessage.addListener( function(request, sender, sendResponse) { if (request.greeting == "hello") alert("hello background"); } );
popup.html 代码:
<!doctype html> <html> <head></head> <body> <form> <input type="button" value="sendMessage" onclick="testRequest()" /> </form> </body> </html>
manifest.json :
manifest.json:
{ "browser_action": { "default_icon": "icon.png", "popup": "popup.html" }, "background": { "page": "background.html" }, "permissions": [ "tabs", "http://*/*", "https://*/*", "notifications", "contextMenus" ], "content_scripts": [ { "matches": ["http://*/*","https://*/*"], "js": ["content.js"] } ], "name": "FirstExtension", "version": "1.0" }
请帮助!
Please help!
推荐答案
sendRequest / onRequest 被替换为 sendMessage $ c $在Chrome 20中,c> / onMessage 。 * Message 不仅仅是的请求,这是一个不同的nt API。
sendRequest/onRequest is replaced with sendMessage/onMessage in Chrome 20. *Message is not just an alias for *Request, it's a different API.
如果您要支持Chrome< 20(许多Ubuntu用户仍在Chromium 18上,因为PPA未更新),请使用 onRequest 和 sendRequest 。否则,请使用 * Message 方法。
If you want to support Chrome <20 (many Ubuntu users are still at Chromium 18, because the PPA is not updated), use onRequest and sendRequest. Otherwise, use the *Message methods.
另一个问题是您的功能位于后台页面,并在弹出窗口中进行调用。这些是不同的范围,如果您想从弹出窗口调用背景页面方法,请使用:
Another problem is that your function is located in the background page, and the call is made in the pop-up. These are different scopes, if you want to call a background page method from the popup, use chrome.extension.getBackgroundPage():
chrome.extension.getBackgroundPage().testRequest();
最后说明:您正在使用清单版本1和内联事件处理程序。此做法已弃用,有关更多信息,请参阅。
Final note: You're using manifest version 1 and inline event handlers. This practice is deprecated, for more information, see http://code.google.com/chrome/extensions/manifestVersion.html.
这篇关于Chrome扩展程序:内容脚本和background.html之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!