簡體   English   中英

使用 chrome.webRequest api 時,網址不會被阻止

[英]urls are not blocking while working with chrome.webRequest api

我在 chrome.storage.sync 中存儲了一些網址,如下所示......

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

現在我正在嘗試使用下面的代碼阻止這些網址.....

清單.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
  },
  
 }

背景.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'] );   

但是 URL 沒有被阻止,我不知道是怎么回事......請幫我解決我面臨的確切問題............

我自己在我的代碼中發現了問題..

實際上這里的問題是chrome.storage.sync的回調是異步函數。 由於chrome.webRequest的回調在chrome.storage.sync的回調返回之前終止。

解決方案可以是,

將所有內容放在chrome.storage.sync的回調中,這樣每個 function 都會在chrome.storage.sync的回調執行后返回。

最后我用下面的修改代碼解決了這個問題......

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'] ); 

});

實際線索來自相關查詢

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM