0

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.

  • It's hard to tell why `swapStyleSheet` doesn't work without its code, so here's an example https://stackoverflow.com/questions/19844545/replacing-css-file-on-the-fly-and-apply-the-new-style-to-the-page – An0num0us Jun 23 '18 at 08:35
  • Oh my god thank you for pointing that out. I have something similar as in the link you have posted. I have updated the original post @Whatever – Cassiopeia Jul 06 '18 at 21:08
  • Your code correctly changes the `href` attribute. I tested it with SO's stylesheet (replaced url) and the styles changed without any problems. Looks like the file is only accessible to your localhost. There is no way it could work if you tried accessing the file hosted on your local server outside of it. Host it elsewhere and try again. – An0num0us Jul 07 '18 at 08:58

0 Answers0