Mykee
Mykee

Reputation: 1

Chrome Extension with JavaScript, for changing CSS

as many others, I've started to do a Chrome Extension, which should change the CSS of a specific page.
I've read the other threads, but what I want to do is a bit more complicated than the other. On the webpage I would like to change the style, there's a select list, with one, or more options.
Basically this looks like the following:
<select id="users"><option value="123">Username</option></select>
The '123' is the user's ID, unique for everyone.

So what I would like to do, is to insert the CSS file, based on the user ID. So I'd like to insert the new CSS like:
//mysite/myfolder/cssfiles/ #userID# .css

My problem is that the page I'd like to customize is not mine, so I can't do this on the server-side, but I'd like to do an Extension for my co-workers to feel a bit unique every time they look at the webpage.

In the manifest.json file, the following content_script runs now:

"content_scripts": [
{
"js": ["myscript.js"]
}
]

and my myscript.js is the following:

var user = document.getElementById("users");
var id = user.options[user.selectedIndex].value;
var name = user.options[user.selectedIndex].text;
var showinfo = alert("Userid: " + id + "\nUsername: " + name);

When the page loads, the alert shows the data correctly, but I haven't figured out yet how could I use them to insert my CSS.

I've also put next to the "js": part for testing purposes the "css": ["mystyle.css"] but this is one pre-definied style, and doesn't depends on the selected user, however it makes the page looks like how I wanted and have written it in the CSS.

Upvotes: 0

Views: 767

Answers (1)

aclave1
aclave1

Reputation: 1712

The easiest way to do this would be something like:

var id = window.prompt("Enter your id","default");
var filepath = id + ".css";
chrome.tabs.insertCSS(tabId,{file:filepath});

Note that this requires the tabs permission in your manifest.

Upvotes: 1

Related Questions