检查字符串的当前选项卡

时间:2013-04-09 08:56:41

标签: javascript google-chrome google-chrome-extension

我的扩展程序正在使用页面操作(仅在twitter.com上提供),我希望在地址栏中显示图标(并且功能至少为空)但我无法使其正常工作。 我使用了documentation sandwich sample并对其进行了修改,看起来像这样:

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

我不确定为什么它不起作用,我不知道如何使用chrome.tabs.query()url属性以及如何针对*://twitter.com/ *进行检查。

1 个答案:

答案 0 :(得分:1)

您应该查看Page Action by Url示例时链接并使用了Page Action by Content示例。您在background页面中所需要的只是:

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

如果您只想查看网址,则无需使用content script

编辑:如果您只想针对当前标签进行测试,那么您可以执行以下操作:

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