tgun926
tgun926

Reputation: 1633

Modify CSS before page loads in chrome extension?

I want to prevent an specific background-image being displayed on a page, possibly using jquery. However, the page and DOM is loaded before the JS is activated.

What I want to do is the following:

.pagelayout-login #page{
background: none;
}

I have tried the same in JQuery using:

$(document).ready(function(){

$(".pagelayout-login #page").css("background","none");

});

However, both modify the stylesheet after the image has been loaded and displayed.

If I add "run_at : "document_start" inside my content scripts, the CSS get's overridden by the page's CSS.

Is there a way to prevent the background from being displayed before it starts loading?

Upvotes: 0

Views: 2388

Answers (3)

user3466437
user3466437

Reputation: 391

Since this is in a Chrome extension, don't be afraid to use !important to ensure that your CSS overrides the page's CSS even if you "run_at : "document_start":

.pagelayout-login #page{
background: none !important;
}

This may or may not prevent the image from loading since it's still being referenced by the page's CSS, but it will at least prevent it from displaying right away. You will need to conduct your own tests to determine if Chrome will still attempt to request the image during page load in spite of this.

Upvotes: 0

Intuitisoft
Intuitisoft

Reputation: 1417

you can add the CSS at the beginning :

chrome.tabs.insertCSS(tab.id, {code:'my css code', allFrames:false, runAt:"document_start"});

or add a script at the end like this :

chrome.tabs.executeScript(tab.id, {code:'my script code', allFrames:false, runAt:"document_end"});

with the CSS, you need to be the first, because it's a "Cascading Style". with the script, it must be the last change.

You can try to add !important to your CSS.

Upvotes: 2

Max Langerak
Max Langerak

Reputation: 1207

I'd think this would be a lot easier the moment you remove the $(document).ready, everything inside that function runs after the page has completed loading.

Upvotes: 0

Related Questions