0

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

  1. which is better way to do the check for prevention of multiple injection
  2. in style 2, am I doing it wrong?
Ani
  • 265
  • 1
  • 3
  • 10
  • No, it's a false claim because typeof won't work with `const`. Use the first variant. – wOxxOm May 08 '23 at 11:16
  • ok, thank you @wOxxOm. Is const the problem? meaning if I use a let injected_check_variable = true, will that be good? (I could not get let to work too) – Ani May 08 '23 at 11:27
  • 1
    @ani a `const` is scoped inside the block where it's declared. The `typeof` check is running _outside_ that block, so the variable will not exist there. – robertklep May 08 '23 at 12:04
  • @robertklep, thank you for reply. tried something on lines: if (typeof focus_event_listner_installed === 'undefined') {....}else {...} let focus_event_listner_installed = false. It gives error "Cannot access 'focus_event_listner_installed' before initialization". Going with wOxxOM's solution – Ani May 08 '23 at 15:57

0 Answers0