coriandres coriandres - 1 year ago 127
HTML Question

Chrome extension: Modifying the content of a webpage

I'm trying to make a simple Chrome Extension where I will 'block' the content of the website Reddit by replacing it with a short text. This is what I have so far:


"manifest_version": 2,

"name": "BlockIt",
"description": "Block Reddit, increase productivity!",
"version": "1.0",

"browser_action": {
"default_icon": "icon.png",
"default_title": "BlockIt"

"permissions": [
"storage", "tabs",

"content_scripts": [
"matches": [ "*://*" ],
"js": ["content-script.js"]


<!doctype html>
body {
font-family: Verdana, Arial, Helvetica, Tahoma, sans-serif;
margin: 5px 5px 5px 5px;
width: 110px;
height: 100%;
<script src="popup.js"></script>
<script src="content-script.js"></script>
<div id="en"><label for="enable">Enable BlockIt</label> <input id="enable" type="checkbox" style="vertical-align:middle; position:relative; bottom: 1px;"/>


document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#enable').addEventListener('change', changeHandler);

function changeHandler() {
if (enable.checked) {{ 'enable': true }, function () { });


var content = document.getElementsByTagName("body");
var text = "BlockIt enabled (to disable, click on the icon).";
//TODO: replace content with text

I'm having two major issues right now: I'm not sure how I should go about in modifying the content of the webpage and replace it with the
above, and I'm not sure how to inject
when the checkbox in
is checked. How do I go about in approaching this?

Answer Source

One possibility would be to use to get the enabled status at the time the content-script.j is injected into the page:

content-script.js:{enable:false}, items=> {
    if(items.enable) {
        document.body.textContent="BlockIt enabled (to disable, click on the icon).";

This is not reversible for the current page. Given that your users will probably expect the block to be reversible without having to reload the page, you might want to consider a different method of accomplishing your block than to replace all of the content.

In addition, this will only replace the <body> for pages which are loaded after the block is enabled. It will not affect pages which are already loaded. You will probably want to use chrome.tabs.query() to get a list of tabs which are currently showing You will then need to inject the script again using chrome.tabs.executeScript().

Something like:

//This requires the "tabs" permission.
//Execute after you have stored the data to (e.g. in the callback)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download