Reputation: 143
I've been teaching myself how to create extensions, with a view towards using them for CSS injection (and eventually SVG injection with CSS as the carrier, but that's a problem for another day).
Here's my current code:
manifest.json
{
"name": "SVG Extension Attempt",
"version": "1.0",
"description": "SVG filter please...",
"permissions": ["activeTab", "declarativeContent", "storage"],
},
"browser_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
},
{
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
},
"manifest_version": 2
}
popup.html
<!DOCTYPE html>
<html>
<head>
<style>
button {
height: 30px;
width: 60px;
outline: none;
background-color: magenta;
}
</style>
</head>
<body>
<button id="changeColour">Change colour</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
let changeColour = document.getElementById('changeColour');
function addStyleString(str) {
var node = document.createElement('style');
node.innerHTML = str;
node.setAttribute('id', 'inserted-style');
document.body.appendChild(node);
}
changeColour.onclick = addStyleString('body {filter: blur(5px);}');
So far I've managed to get the extension to run but discovered that, rather than injecting the CSS snippet into the body of the current webpage, it instead injects it straight into the body of popup.html. See gif:
I know this has something to do with popup.js being called in popup.html, but I can't see a workaround myself at the moment - but I just know it's going to be something mind-blowingly simple.
(P.S. it's only these three files because this is basically a practice to learn how to use this injection technique)
Upvotes: 1
Views: 118
Reputation: 18378
You need to execute the code in tab. To do so change your popup.js like this:
let changeColour = document.getElementById('changeColour');
function addStyleString(str) {
// preparing the code as a string
var code = `
var node = document.createElement('style');
node.innerHTML = '${str}';
node.setAttribute('id', 'inserted-style');
document.body.appendChild(node);
`;
// executing the code
chrome.tabs.executeScript(null, {code: code});
}
changeColour.onclick = addStyleString('body {filter: blur(5px);}');
Upvotes: 2