Im trying to have my code to be injected using the content script method for google chrome extensions. This only works when my manifest does not have a Popup page and my background.html has this:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: "jquery.js" }, function() {
chrome.tabs.executeScript(null, { file: "content_script.js" });
});
});
How can I have this code be triggered every time a new page has been loaded in chrome while having a PoPup page? because so far the only way that it works is when I click the browser action button of the extension.
Also in my content script section of manifest I have included all this:
"content_scripts": [
{
"matches": ["http://jquery.com/*"],
"all_frames":true,
"js": ["jquery.js","jquery-ui.min.js","content_script.js"],
"run_at": "document_end"
}
],
Short answer: Use chrome.tabs.onUpdated.addListener
instead of chrome.browserAction.onClicked.addListener
from the background page to load the content script every time the page is updated.
Long answer: You CAN in fact have a content script be loaded when their is a popup page, either by including the content script from the manifest or using programmatic injection from the background page (as you suggested in your question).
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["http://myurl.com/*"],
"css": ["mystyles.css"],
"js": ["jquery.js", "myscript.js"]
}
],
"permissions": [
"http://myurl.com/*",
"tabs"
],
"background_page": "background.html",
"browser_action": {
"popup": "popup.html"
}
...
}
Make sure the "matches" property matches the URL for the page you want to load the content script on.
You can use the way you suggested in your question, which will insert the content script when the browser action is clicked OR you could do it every time the browser URL is updated like so:
chrome.tabs.onUpdated.addListener(function() {
chrome.tabs.executeScript(null, { file: "jquery.js" }, function() {
chrome.tabs.executeScript(null, { file: "content_script.js" });
});
});
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