chrome extension: Injecting code which references a script that I am also injecting - why it fails?

孤人 提交于 2020-01-07 04:37:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!