Dynamic loading of content script (chrome extension)

蹲街弑〆低调 提交于 2019-12-05 04:51:35

This means, probably, that you're getting an onUpdated event on an extension/internals page (popup? options page? detached dev tools?).

One option is to filter by URL:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if(changeInfo.status == "complete") {
        if(!tab.url.match(/^http/)) { return; } // Wrong scheme
        var filename = getSpecificFilename(url);
        chrome.tabs.executeScript(tabId, {file: filename}, function() {
            //script injected
        });
    }
});

Another (and probably better) option is to make your content script request this injection:

// content script
chrome.runtime.sendMessage({injectSpecific : true}, function(response) {
  // Script injected, we can proceed
  if(response.done) { apply_forms(/*...*/); }
  else { /* error handling */ }
});

// background script
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  if(message.injectSpecific){
    var filename = getSpecificFilename(sender.url);
    chrome.tabs.executeScript(sender.tab.id, {file: filename}, function() {
      sendResponse({ done: true });
    });
    return true; // Required for async sendResponse()
  }
});

This way you know that a content script is injected and initiated this.

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