简体   繁体   中英

chrome webrequest api array of urls?

Here is the code for a very simple chrome extension that blocks manually specified websites.

chrome.webRequest.onBeforeRequest.addListener(function(details) { 
    return {cancel: true}; 
},
{urls: ["*://*.google.com/*", "*://*.facebook.com/*"]},
["blocking"]);

I'm wondering if it's possible to make this url list equal to an array of websites, and if so what the syntax is. My goal is to retrieve a list of websites from a websocket server, then have my chrome extension block them. Here is my code.

var testSocket = new WebSocket("http://www.example.com/socketserver");
testSocket.onmessage = function (e) {
     var websites = e.split(',');
     console.log(e);
}

I'm new to javascript, but I believe this should allow me to connect to an "example.com" websocket server, retrieve a string of urls separated by commas, and split the string into an array named "websites."

Assuming the above code does what I just described (and please tell me if it does not), how do I set "urls" from the chrome extension equal to "websites"?

  • Make the webRequest listener a global function and re-register it upon receiving the list.
  • Also, save/load the list in chrome.storage.local

function blockUrl(details) { 
  return {cancel: true}; 
}

// load the list on extension startup
chrome.storage.local.get('urls', data => {
  if (data.urls && data.urls[0]) {
    chrome.webRequest.onBeforeRequest.addListener(blockUrl, data, ['blocking']);
  }
});

testSocket.onmessage = function (e) {
  const urls = e.split(',');
  chrome.storage.local.set({urls});
  chrome.webRequest.onBeforeRequest.removeListener(blockUrl);
  if (urls[0]) {
    chrome.webRequest.onBeforeRequest.addListener(blockUrl, {urls}, ['blocking']);
  }
};

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