问题
I am trying to create a jquery popup on any page, triggered on demand, when the user presses on my chrome extension.
I have permissions set to [ "tabs", "http:///", "https:///" ]
I have a background page which tries to do the following:
chrome.browserAction.onClicked.addListener(function(tab) {
//chrome.tabs.executeScript(null, { code: "alert(document.title);" }, null);
chrome.tabs.executeScript(null, {file: "demo.js"}, null);
chrome.tabs.executeScript(null, { code: "document.body.appendChild(document.createElement('script')).src='demo.js'" }, null);
});
If I uncomment the alert, it appears when I click on the extension icon. But with the comment as it is it doesn't do anything.
Any thoughts why it fails?
UPDATE I managed to get it working, by referencing a url and not a local resource(demo.js). Now the code, that works, looks like this:
chrome.tabs.executeScript(tab.id, { code: "document.body.appendChild(document.createElement('script')).src='http://iamnotagoodartist.com/stuff/wikiframe.js'" }, null);
My local "demo.js" was a copy of the content from that url anyway. I am not sure why it doesn't work when I reference the local file... ?
回答1:
You must use chrome.extension.getURL to get the full path to the "demo.js" file.
chrome.tabs.executeScript(null, {
code: "document.body.appendChild(document.createElement('script')).src='" +
chrome.extension.getURL("demo.js") +"';"
}, null);
BTW if you set tabId parameter to null, the script won't be injected into the background page but into the selected tab of the current window.
回答2:
You are not passing the tab
id to executeScript
so the scripts are getting injected into the backround page where you can't interact with them.
chrome.tabs.executeScript(tab, {file: "demo.js"}, null);
来源:https://stackoverflow.com/questions/8293465/chrome-extension-injecting-code-which-references-a-script-that-i-am-also-inject