Search code examples
javascriptgoogle-chrome-extension

reloading chrome extension fails because symbols already defined. How to avoid this?


I have written a Chrome extension that takes a screenshot of a Go (a board game) board and then downloads the screenshot to the local system.

Although the extension works, I cannot invoke the extension twice in a row without reloading the page because if I attempt to do so, I get the error:

Uncaught SyntaxError: Identifier 'BadukFlash' has already been declared (at baduk_flash.js:1:1)

Solution

  • When the user clicks on the action, the extension injects html2canvas.js and baduk_flash.js into the active tab.

    baduk_flash.js declares the class BadukFlash.

    When the user clicks the action again, all of this happens again. I.e. the class BadukFlash is re-declared.

    At this point, baduk_flash.js stops executing, because of this uncaught syntax error. If baduk_flash.js were to continue running, then the variable bf would also be re-declared.

    Possible ways to fix this:

    The cleanest way would be to inject the content script with static declarations, by using the field "content_scripts" in manifest.json:

    https://developer.chrome.com/docs/extensions/mv3/content_scripts/#static-declarative

    When the user clicks the action, the service worker should send a message to the content script in the active tab.

    But then you have to know in advance what pages you want to inject the content script into. If you don't know that, you must inject it programmatically, and check if it's already been injected:

    How can I prevent multiple injection/execution of content script(s) in response to a single event?