Friday, May 17, 2024
116
rated 0 times [  120] [ 4]  / answers: 1 / hits: 18198  / 12 Years ago, wed, august 1, 2012, 12:00:00

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 code:



<!doctype html>
<html>
<head></head>
<body>
<form>
<input type=button value=sendMessage onclick=testRequest() />
</form>
</body>
</html>


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!


More From » google-chrome-extension

 Answers
3

sendRequest/onRequest is replaced with sendMessage/onMessage in Chrome 20. *Message is not just an alias for *Request, it's a different API.



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();


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.


[#83934] Monday, July 30, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
victorr questions
Fri, Nov 13, 20, 00:00, 4 Years ago
Sat, Jul 25, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;