I have a very simple chrome extension, where I'm trying to pass a message from the background script to the content script. But chrome.runtime
is undefined.
Here's literally all the code, as you can see there's almost nothing to it. In the content script, runtime is undefined.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.runtime.sendMessage({action: 'someAction'},
function(response) {
console.log('Response: ', response);
});
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
sendResponse({
user: 'user'
});
});
{
"manifest_version": 2,
"name": "My Extension",
"version": "1.0",
"description": "Some stupid extension",
"browser_action": {
"default_icon": "icons/MyExtensionIcon.png"
},
"icons": {
"48": "icons/MyExtensionIcon.png"
},
"permissions": [
"tabs",
"storage",
"https://*/",
"http://*/"
],
"content_scripts": [
{
"matches": ["*://*.twitter.com/*", "https://twitter.com/*"],
"js": ["js/content.js"]
}
],
"background": {
"scripts": ["js/background.js"],
"persistent": true
},
"web_accessible_resources": [
"js/*",
"css/*"
]
}
Other Info:
Head to More tools > Extensions. Use the toggle for each extension to turn it off. Restart Chrome and go back to the extensions list. Re-enable the extensions.
Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them, and pass information to their parent extension.
Description Use the chrome.runtime API to retrieve the background page, return details about the manifest, and listen for and respond to events in the app or extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs.
chrome.tabs is only available in background scripts and popup scripts. If you wanna to use chrome.tabs then pass message from content_script to background script and play with chrome.tabs. Content scripts have only limited access to Chrome APIs. This access does not include chrome.tabs.
Content scripts have only limited access to Chrome APIs. This access does not include chrome.tabs. If you need to use chrome.tabs, you will have to do so in a background script1.
Content scripts can access Chrome APIs used by their parent extension by exchanging messages with the extension. They can also access the URL of an extension's file with chrome.runtime.getURL () and use the result the same as other URLs. var imgURL = chrome. runtime.getURL("images/myimage.png");
Ok I figured it out. It's absolutely stupid, but it appears this is simply a Heisenbug. By adding a breakpoint, or debugger statement, it causes that value to be undefined. Maybe a chrome bug?
I swear, every day Chrome feels more, and more like Internet Explorer.
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