Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content scripts being executed multiple times in Chrome Extension

Currently, we have a content script which is initialised in the manifest.json file as follows:

"content_scripts": [
    {
    "matches": [
        "https://docs.google.com/*"
        ],
    "js ["content.js"],
    "run_at": "document_start",
    "all_frames": true, 
    "match_about_blank": true      
    }

],

which is set to run every time the user loads up a google docs document. However, by looking at the console logs it seems as if the content script is loaded (is the correct word injected?) into the new tab multiple times, as we get multiple console logs.

I've read in some other answers that this may have to do with the fact that the content script is loaded once when the google docs tab is loading, and once when it has finished loading, so it runs multiple times; though how do I prevent this from happening?

like image 482
Joshua Lin Avatar asked Nov 05 '16 12:11

Joshua Lin


1 Answers

The problem is "all_frames": true. Google Docs embeds many iframes from the same domain:

<iframe src="https://docs.google.com/document/u/0/preload" style="display:none;" tabindex="-1"></iframe>
<iframe src="https://docs.google.com/offline/iframeapi?ouid=REDACTED#cd=1" style="display: none;"></iframe>

Your content script is getting injected into all of these frames.

If you set "all_frames": false: your content will only get injected in to the top frame, and will log just once upon browsing to a Google Docs document.

like image 119
Birchlabs Avatar answered Oct 29 '22 02:10

Birchlabs