javascript - 使用页面操作在特定页面上显示 Chrome 扩展程序

标签 javascript google-chrome google-chrome-extension

我正在尝试为 Pinterest 制作一个 chrome 扩展。

我按照从 Chrome 扩展 sample 中找到的示例进行操作(当网址中有“g”时,在多功能框中显示图标)并对文件进行了一些更改,使其在网站中有“pinterest.com”时显示图标。这是代码:

ma​​nifest.json:

"permissions": [
    "tabs", 
    "http://*.pinterest.com/"
]

background.js,我从网上的示例中复制了大部分代码:

function showPinterestAction(tabId, ChangeInfo, tab) {
  if(tab.url.indexOf('pinterest.com') > -1){
    chrome.pageAction.show(tabId);
  }
  /* This doesn't work. tab.url return undefine to me :( */
};

chrome.tabs.onUpdated.addListener(function(tabId, change, tab) {
  if (change.status == "complete") {
    showPinterestAction(tabId);
  }
});

chrome.tabs.onActivated.addListener(function(tabId, info) {
  selectedId = tabId;
  showPinterestAction(tabId);
});

// Ensure the current selected tab is set up.
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  alert(tabs[0].id);
  showPinterestAction(tabs[0].id);
});

右侧页面没有显示图标。如果我尝试alert(tab.url),它会给出undefined。有人可以告诉我我的代码有什么问题吗?

最佳答案

好吧,您仅使用一个参数 tabId 来调用 showPinterestAction

因此,tab 参数只是未定义,这并不奇怪。 showPinterestAction 的签名遵循 tab update callback ,但你并没有像使用它那样使用它。

您可以将 showPinterestAction 修改为 pull the data它需要:

function showPinterestAction(tabId) {
  chrome.tabs.get(tabId, function(tab){
    if(tab.url.indexOf('pinterest.com') > -1){
      chrome.pageAction.show(tabId);
    }
  });
};

您可能还想让您的匹配模式更加通用:"*://*.pinterest.com/*" 应该涵盖您的用例。

<小时/>

或者,您可以使用declarativeContent API,而不是锁定多个选项卡事件。 - 它是为此而创建的。

var rule = {
  conditions: [
    new chrome.declarativeContent.PageStateMatcher({
      pageUrl: { hostSuffix: 'pinterest.com' }
    })
  ],
  actions: [ new chrome.declarativeContent.ShowPageAction() ]
};

chrome.runtime.onInstalled.addListener(function(details) {
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules([rule]);
  });
});

在这种情况下,您不需要像“选项卡”这样的“重”权限或主机权限。您的 list 只需要

"permissions": [
   "declarativeContent", 
   "activeTab"
]

为了让它发挥作用。

关于javascript - 使用页面操作在特定页面上显示 Chrome 扩展程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28062009/

相关文章:

javascript - 访问 HTMLcollection 时获取 null

javascript - 如何捕获或收听浏览器通知?

android - 为 Android 的默认浏览器或 Chrome 构建插件

javascript - Chrome Google 帐户注销或 Google 帐户用户切换事件

javascript - Fullpage.js - 点导航样式

javascript返回两个对象之间的差异

javascript - 拉斐尔 Javascript。更改与另一个对象相关的文本外观

google-chrome - 检查新 Chrome 中的下拉菜单

javascript - 如何在 Chrome 扩展程序卸载/禁用时清理网页

google-chrome - 在安装之前,是否可以检查Google Chrome扩展程序的代码?