Question

I am working on the extension that needs to update page texts after page is loaded. I use window.onload in "content_script".

As I need to test my changes a lot I decided to create a little page with a few paragraphs of text and put it in my web server. But when this page loads - extension's window.onload doesn't trigger, wheres on any other internet page it works properly.

I started investigation and found out, that this is because of the page loading speed. So basically page loads faster than extension code.

It was verified by adding background image on the body linked to the external site. Like this:

body
{
    background: url(http://colourunity.com/img/2013/07/autumn-wallpaper-computer-14172-hd-widescreen-wallpapers.jpg) no-repeat;
}

So the page's loading speed slows down and extension has enough time to load in and window.onload triggers.

Of course I don't worry about extension work, because it is too rare case when page loads that fast.

But still - is there anyway to bypass this?

Thanks.

Was it helpful?

Solution

The window object of your content script is not the same as the one of your page. From the content script documentation:

It's worth noting what happens with JavaScript objects that are shared by the page and the extension - for example, the window.onload event. Each isolated world sees its own version of the object.

Therefore listening for this event in your content script won't work as you intent, since it's not the one you want.

It doesn't matter anyway: you can specify at which point your script is executed via the run_at option. For example, if you choose to run it at document_idle, then you're guaranteed it's executed after the window.onload event of your page.

In other words, you can simply stop using the window.onload event, and directly run the code you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top