开发者

How to match a URL from a tab with an Array of URL's - Google Chrome Extension

开发者 https://www.devze.com 2023-03-15 08:51 出处:网络
So far I have this: // So we can notify users var notification = webkitNotifications.createNotification(

So far I have this:

// So we can notify users
    var notification = webkitNotifications.createNotification(
    'icon-48.png',  
    'Alert!', 
    'abcdefghijklmnop'
);
      // Called when the url of a tab changes.
      function checkForValidUrl(tabId, changeInfo, tab) {
        // Compare with a the URL
        if (tab.url.indexOf('example.com') > -1) {
          //then
          chrome.pageAction.s开发者_开发技巧how(tabId);
          notification.show();
        }
      };

      // Listen for any changes to the URL of any tab.
      chrome.tabs.onUpdated.addListener(checkForValidUrl);

Instead of simply comparing with example.com as above I would like to check the URL against an Array of URL's. How would I do this?


The same, except you would loop through the array:

function checkForValidUrl(tabId, changeInfo, tab) {
  for (var i = 0, iLen = urlArray.length; i < iLen; i++) {
    if (tab.url.indexOf(urlArray[i]) > -1) {
      chrome.pageAction.show(tabId);
      notification.show();
      break; // halt for loop
    }
  }
};

Another option would be to use a regular expression and use if (tab.url.match(re)) instead, where re could be something like /example\.com|example\.org|google\.com/.


If the array is small you can just iterate over it and check.
If it's significantly bigger, Your best method would be to pre-sort it and do a binary serach on it.

Another option can be to concatenate your array to a single string and then just check for an existance in this string (either with indexOf or with regex)

0

精彩评论

暂无评论...
验证码 换一张
取 消