简体   繁体   中英

JQuery Chrome Extension, unable to change css attribute

I have a simple chrome extension that I use on one URL to change the layout of a page very slightly (color, position etc)

I'm trying to do the same on a new URL. The code I'm using for both is the same and it works fine on one URL but not another.

This is the failing code. I've replaced the actual URL with SITE in this post.

var url = window.location.href;
if (url.toLowerCase().indexOf('SITE') >= 0) {   
    console.log ('Amending CSS');

    $('.main-container').css({"background":"red"});

}

The element I'm trying to change is: <clr-main-container _ngcontent-c0="" class="main-container">

Checking my console I see 'Amending CSS' but nothing appears to have changed.

The URL is accessed via HTTPS and is a firewall, so I'm not sure if there is a way they could block changes or not.

Any one any ideas on this thanks :)

I think you might need to wrap your code in

$(document).ready(function() {
// your code
});

This will wait for the page to be ready before it runs the code, hopefully ensuring the element is on the page.

May i also recommend the chrome extension, Stylebot. It allows you to apply custom CSS to any website, and it will remember it for future visits.

I'm trying the same and it's working for snippet website check:

 $(function(){ var url = window.location.href; console.log(url); if (url.toLowerCase().indexOf('stacksnippets') >= 0) { console.log ('Amending CSS'); $('body').css({"background":"red"}); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If the previous code didn't work with this might be due to a css on the same element with higher priority !important

check this:

 $(function(){ var url = window.location.href; console.log(url); if (url.toLowerCase().indexOf('stacksnippets') >= 0) { console.log ('Amending CSS'); $('body').addClass("red_bg");; } });
 .red_bg { background:red !important; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

喜欢就点个赞

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM