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

徘徊边缘 提交于 2020-01-11 09:29:09

问题


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 page (per the example in the documentation):

chrome.browserAction.onClicked.addListener(function callback(tab){
  chrome.tabs.executeScript(null, {file: "content-script.js"});
});

However, the way this works, the script is injected every time the button is clicked.

How can I change it so that the script is not injected on subsequent button presses - so that it is inserted only the first time the button is clicked on that page?


回答1:


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

if (something) { return; }



回答2:


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"});
}});


来源:https://stackoverflow.com/questions/18477232/how-do-i-make-it-so-my-chrome-extension-will-only-inject-a-script-once

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