I am looking for best practice to prevent injection my javascript multiple times. The background script has code like to insert injected.js
chrome.scripting.executeScript({
target: {tabId: tab.id},
files: ['content/injected.js']
})
On stackoverflow + other sites I see two options to prevent multiple injections
1.Based on this stackoverflow reply from @wOxxOm, injected.js variant 1 is
if (window.contentScriptInjected !== true) {
window.contentScriptInjected = true; // global scope
const focus_event_listner = () => {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "StartTimer") {
console.log('injected.js: start timer')
}
});
console.log(document.title, ": has now been injected")
}
focus_event_listner()
} else {
console.log(document.title, ": was already injected")
}
this code works!!
2.However, somewhere (i cannot find the link), it said better to use typeof. So the injected.js variant 2 is
if (typeof focus_event_listner === 'undefined') {
const focus_event_listner = () => {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "StartTimer") {
console.log('injected.js: start timer')
}
});
console.log(document.title, ": has now been injected")
}
focus_event_listner()
} else {
console.log(document.title, ": was already injected")
}
This code does NOT work. The questions are
- which is better way to do the check for prevention of multiple injection
- in style 2, am I doing it wrong?