Swapping foreign site Css on the fly using Tampermonkey

291 views Asked by At

I am trying to write a very basic (user)script for a game site (skribbl.io), where I add a div at the top of the site that should act as a lightswitch (dark mode on/off).

When I try to hot-swap a CSS file in oder to alter the style of my local webpage, I have no problems, but once I go over to my userscript, it won't work.

I get no errors in the console and on clicking the div I can see that the href of the link element does in fact change, as expected -- the catch: the site's appearance does not change.

Here's my userscript code:

var lightSwitch = document.createElement('div'); 
//Inserting it at the top of the page
document.body.insertBefore(lightSwitch, document.body.children[2]); 

//I have to get and modify the <link> tag because by default it has no Id
var linkElement = document.getElementsByTagName('link')[0];
linkElement.setAttribute("id", "pagestyle");

function swapStyleSheet(sheet) {
  var link = document.getElementById("pagestyle");
  link.setAttribute("href", sheet);
}

lightSwitch.addEventListener('click', function(){
     swapStyleSheet('https://cdn.rawgit.com/externally-hosted-style.css')
}, false);

//GREY DIV STYLING
lightSwitch.style.width = "50px";
lightSwitch.style.height = "50px";
//etc...

Again, this works locally on my HTML test file, but not with Tampermonkey. Why?

Note: It is not just about altering the style of the site, but about having it within my userscript that shall have greater functionalities at some point. Of course I could use other extensions to modify the page's appearance, but in my case that is out of the question.

GM_addStyle would be an idea if I can toggle it with a button or similar. But as you may notice - my Javascript knowledge is non-existent.

0

There are 0 answers