Leslie Wu
Leslie Wu

Reputation: 770

DOMContentLoaded event cannot catch loading of sub frame in Chrome content script

I used DOMContentLoaded event in Firefox extension to catch loading event of every sub-frames in one tab window.

But in Chrome content script, I use

document.addEventListener("DOMContentLoaded", function(evt){console.log('domcontentloaded!')}, true);

It doesn't work, it can only catch loading event of the top window.

So is there anything different here between Firefox and Chrome?

Upvotes: 0

Views: 636

Answers (1)

Xan
Xan

Reputation: 77482

This code should not work as you describe if executed in the top frame, even in Firefox.

The easiest way to achieve this would be to inject your content script in every frame.

Maybe the difference is that Firefox does it by default; in Chrome this is optional. Since the console is shared between frames/contexts, you get the (false!) impression that it comes from code in the top frame.

In the manifest:

"content_scripts" : [
  {
    "matches" : ["<all_urls>"],
    "js" : ["content.js"],
    "all_frames" : true,
    "run_at" : "document_start"
  }
]

Note: I'm putting "document_start" there as well since by default your scripts are injected after that event (so you're not guaranteed to catch it). For more information, see run_at parameter docs.

Using executeScript:

chrome.tabs.executeScript({file: "content.js", all_frames: true});

Upvotes: 2

Related Questions