更新时间:2023-12-05 20:53:22
您必须使用 chrome.extension.getURL 获取完整路径
$ b
chrome.tabs.executeScript(null,{
code:document。 body.appendChild(document.createElement('script'))。src ='+
chrome.extension.getURL(demo.js)+';
},null);
如果将tabId参数设置为null,则脚本不会被注入到背景页面中,但转换为当前窗口的选定标签。
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... ?
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.