简体   繁体   中英

checking current tab against a string

My extension is using a page action (only available on twitter.com) and i wish to make the icon visible (and functional at least empty for now) in the adress bar but i can't get it working. I used the documentation sandwich sample and modified it so it looks like this:

contentscript.js:

// Called when the url of a tab changes.
if(chrome.tabs.query(active(true),function{
  // If the url is twitter
  ( {'url':'https://google.com/google-results-string'}
  if (chrome.tabs.query({'url':'*://twitter.com/*'} , function(tabs){console.log(tabs)}){
    // ... show the page action.
    //chrome.pageAction.show(tabId);
    chrome.extension.sendRequest({}, function(response) {});
  }
};
// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);

background.js

function onRequest(request, sender, sendResponse) {
// Show the page action for the tab that the sender (content script)
// was on.
    chrome.pageAction.show(sender.tab.id);

// Return nothing to let the connection be cleaned up.
    sendResponse({});
};

// Listen for the content script to send a message to the background page.
chrome.extension.onRequest.addListener(onRequest);

I'm not sure why it's not working and i'm not sure how to use the chrome.tabs.query() url attribute and how to check it against * ://twitter.com/ * .

You linked and used the Page Action by Content example, when you should have been looking at the Page Action by Url example. All you need is something like this in your background page:

function checkForValidUrl(tabId, changeInfo, tab) {
  if (tab.url.indexOf('twitter.com') > -1) {
    chrome.pageAction.show(tabId);
  }
};
chrome.tabs.onUpdated.addListener(checkForValidUrl);

There is no need to use a content script if you just want to check the url.

Edit: If you only want to test against the current tab then you can do something like this:

chrome.tabs.onUpdated.addListener(function(tabId,info,tab){
  if(tab.active){
    if (tab.url.indexOf('twitter.com') > -1)
      chrome.pageAction.show(tabId);
  }
});

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