简体   繁体   中英

urls are not blocking while working with chrome.webRequest api

I have stored some urls in chrome.storage.sync like below......

sitesToBeBlocked: {
   "https://www.google.com/":"https://www.google.com/" ,
   "https://www.example.com/": "https://www.example.com/"
}

Now i am trying to block these urls using the code below.....

Manifest.json

{
  "name": "chrome extension",
  "description": ".............",
  "version": "0.0.1",
  "manifest_version": 2,

  "background": {
    "scripts": ["/scripts/background/background.js"]
  },

  "content_scripts": [
    {
      "matches": ["https://*/*","http://*/*"] ,
      "js": ["/scripts/content/jquery-3.6.0.js","/scripts/content/content-script.js"]
    }
  ],

  "permissions": ["storage","unlimitedStorage","webRequest","webRequestBlocking","*://*/*"],

  "browser_action": {
    "default_popup": "/popup/popup.html",
    "default_icon": {
      ............
    }
  },

  "options_ui": {
      "page": "/options/options.html",
      "open_in_tab": true
  },
  
 }

background.js

function isRequestCancelled(sitesArray, url){
    return sitesArray.includes(url);
}

function blockListener (details) {
    chrome.storage.sync.get(null, (items)=>{
        var sitesArray = Object.keys(items['sitesToBeBlocked']);
        
        return { cancel: isRequestCancelled(sitesArray, details.url ) };
    });  
}
chrome.webRequest.onBeforeRequest.addListener( blockListener ,{ urls: ["<all_urls>"], types: [ 'main_frame' ] }, ['blocking'] );   

But URLs are not blocked , I don't know what is the matter... please help me to get the exact problem that i am facing............

I figured out the problem in my code myself..

Actually the problem here is that chrome.storage.sync 's callback is asynchronous fucntion. Due to which chrome.webRequest 's callback is terminated before chrome.storage.sync 's callback return.

The solution can be,

Put everything inside chrome.storage.sync 's callback, so that every function will return after chrome.storage.sync 's callback executes.

Finally I have fixed this issue with the modified code below....

chrome.storage.sync.get(null,(items)=>{

  function isRequestCancelled(sitesArray, url){
    return sitesArray.includes(url);
  }

  function blockListener (details) {
     var sitesArray = Object.keys(items['sitesToBeBlocked']);
     return { cancel: isRequestCancelled(sitesArray, details.url ) };
  }
  chrome.webRequest.onBeforeRequest.addListener( blockListener ,{ urls: [" 
  <all_urls>"], types: [ 'main_frame' ] }, ['blocking'] ); 

});

Actual clue is got from related query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM