Editing a Webpage on Chrome: A Guide

The replacement will solely apply for pages that load post the activation of the block. It will not have any impact on the pages that have already been loaded.


Solution 1:

To obtain the enabled status during the injection of the content-script.j into the page, a feasible solution could be to employ

chrome.storage.sync.get()

.

The file named “content-script.js” is present.

chrome.storage.sync.get({enable:false}, items=> {
    if(items.enable) {
        document.body.textContent="BlockIt enabled (to disable, click on the icon).";
    }
});

As the current page’s block cannot be reversed, it may be wise to explore alternative approaches to achieve your desired block without having to reload the page. This is important to consider as your users may anticipate a reversible block without the need for a page refresh.

Moreover, the replacement of

<body>

will solely apply to pages that load after enabling the block and not those already loaded. It is recommended to utilize

chrome.tabs.query()

to obtain a list of the currently displayed

reddit.com

tabs and re-inject the script using

chrome.tabs.executeScript()

.

Something like:

//This requires the "tabs" permission.
//Execute after you have stored the data to chrome.storage.sync (e.g. in the callback)
chrome.tabs.query({url:"*://reddit.com/*"},tabs=>{
    tabs.forEach(tab=>{
        chrome.tabs.executeScript(tab.id,{file:"content-script.js"});
    });
});


Solution 2:


Blocking API request redirection through

webRequest

is a more efficient use of resources.

Suppose you possess a

blocked.html

page that is displayed in lieu of the content.

Let’s say the extension state is stored in

chrome.storage.sync

per Mayken’s suggestion. To ensure synchronous redirection, a synchronous cache of the value is required.

// Background script
var enabled;
function cacheEnabled() {
  chrome.storage.sync.get({enable: false}, data => {
    enabled = data.enable;
  });
}
cacheEnabled();
chrome.storage.onChanged.addListener(cacheEnabled);
chrome.webRequest.onBeforeRequest.addListener(
  details => {
    if (enabled) {
      return { redirectUrl: chrome.runtime.getURL("blocked.html") };
    }
  },
  {
    urls: ["*://*.reddit.com/*"],
    types: ["main_frame", "sub_frame"]
  },
  ["blocking"]
);

Authorization is needed for

"webRequest", "webRequestBlocking", "*://*.reddit.com/*"

.

Please note that the current solution is not ideal. It is preferable to register or unregister the listener based on

enabled

, instead of checking it within the listener. The latter should be done as quickly as possible. However, this is something that you can practice on your own.

Frequently Asked Questions