I am writing a google chrome extension and trying to send information from a piece of code that is injected into a web page to my content script.
According to http://developer.chrome.com/extensions/messaging#external-webpage, I should use something like :
// The ID of the extension we want to talk to.
var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";
// Make a simple request:
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
function(response) {
if (!response.success)
handleError(url);
});
The problem is, when I do :
var script_code = "var msg = {message : 'plop'};\n";
script_code += "chrome.runtime.sendMessage('" + chrome.i18n.getMessage("@@extension_id") + "', msg, function(response) {\n";
script_code += " console.log('response received');\n";
script_code += "});\n";
An then inject this to the webpage, when it is executed, I get :
Uncaught TypeError: Cannot call method 'sendMessage' of undefined
Can anyone help me through this ?
Thanks
javaScript code in Chrome extensions can be divided in the following groups:
Extension code - Full access to all permitted chrome.* APIs.
This includes all extension pages(background page, popup page ,option page, and so on)
Content scripts (via the manifest file or chrome.tabs.executeScript) - Partial access to some of the chrome APIs
Full access to the page's DOM.
Injected scripts (via this method in a Content script) - Full access to all properties in the page. No access to any of the chrome. APIs.*
Execute on the actual page, can't access any of the chrome.* APIs.**.
In your case, code is execute on the actual page, can't call chrome.runtime.* APIs.
Maybe, you can try window.postMessage().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With