How do I make it so my Chrome extension will only inject a script once?

前端 未结 2 715
故里飘歌
故里飘歌 2021-01-13 19:17

I\'m using programmatic injection to inject my extension\'s code into a page only when the browser action is clicked.

This is what I have on my extension\'s event pa

相关标签:
2条回答
  • 2021-01-13 19:48

    Put a gloabl variable in your contentscript to judge if the contentscript has executed.

    if (something) { return; }
    
    0 讨论(0)
  • 2021-01-13 19:53

    One way I can think of right now (easy and simple) is to use html5webstorage. Since you are running this code from your background or popup page it will be ok.

    if(!localStorage.getItem("isAlreadyInjected")){
       localStorage['isAlreadyInjected'] = "true";
       chrome.browserAction.onClicked.addListener(function callback(tab){chrome.tabs.executeScript(null, {file: "content-script.js"});});}
    

    So, the very first time when storage value "isAlreadyInjected" does not exist, the listener will be added. Afterwards, even when the browser closes and opens again this value will remain stored and so the listener will not be added to your extension.

    UPDATE

    As your background page loads only once at the beginning, it can keep variable that is not re-initialized with the browser action click. So you can use that variable to do your job!

    background.js

    var isAlreadyInjected =false;
    function isInjected(){
    
    if(!isAlreadyInjected ){
        isAlreadyInjected=true;
        return false;
     }
     else
        return true;
    }
    

    popup.js

    var bgpage=chrome.extension.getBackgroundPage();
     if(!bgpage.isInjected()){
        chrome.browserAction.onClicked.addListener(function callback(tab) {chrome.tabs.executeScript(null, {file: "content-script.js"});});
    }
    

    or

    var bgpage=chrome.extension.getBackgroundPage();
      chrome.browserAction.onClicked.addListener(function callback(tab) { 
     if(!bgpage.isInjected()){
        chrome.tabs.executeScript(null, {file: "content-script.js"});
    }});
    
    0 讨论(0)
提交回复
热议问题