How to make Chrome extension only enter script once?

I use software injection to enter the extension code on the page only when I click on the browser action.

This is what I have on my extension page (as an example in the documentation ):

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

However, how it works, a script is entered every time a button is pressed.

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

+4
source share
2 answers

Put the gloabl variable in your text to judge whether the text has been processed.

 if (something) { return; } 
+6
source

One way that I can come up with now (simple and simple) is to use html5webstorage . Since you are using this code from your background or pop-up page, everything will be fine.

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

So, for the first time, when the "isAlreadyInjected" storage value does not exist, a listener will be added. After that, even when the browser closes and reopens, this value will remain saved and therefore the listener will not be added to the extension.

UPDATE

Since your background page loads only once at the beginning, it may contain a variable that will not be reinitialized with a mouse click. Therefore, you can use this 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"}); }}); 
+2
source

Source: https://habr.com/ru/post/1499260/


All Articles