【问题标题】:How to observe changes in tab from Google Chrome extension?如何从谷歌浏览器扩展中观察标签的变化?
【发布时间】:2016-04-19 21:55:28
【问题描述】:

我开发了一个 Chrome 扩展程序,可以将一个按钮注入特定网页的富文本编辑器的工具栏中,代码可用 here。这个基本扩展基于“内容脚本”的概念,并且运行良好,因为工具栏在页面加载后立即出现。

但是,现在我遇到了另一个页面,我无法在页面加载后立即注入我的按钮,因为用户需要在工具栏出现之前先与页面交互(进行选择或按下按钮) .

所以我正在寻找一种方法来跟踪活动选项卡中的任何更改(我有一个页面的 URL 模式)。我不想要或不需要浏览器操作(即多功能框右侧的小按钮),所以我希望摆脱 background.js 事件页面,我可以在其中为某些用户声明事件侦听器- 发起的事件,但不知何故它不起作用。

解释一下:我有我的manifest.json,太好了:

{
  "name": "basic tab test",
  "description": "blah di blah",
  "version": "1.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"], // background script shown below
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": [
        "file://*"    // for testing only, of course
      ],
      "js": [
        "contentscript.js" // <-- content script shown below
      ]
    }
  ],
  "manifest_version": 2
}

background.js 脚本现在看起来像这样:

console.log("in background.js");

chrome.tabs.getCurrent(function(tab) {
  tab.onActivated.addListener(function(){
    console.log("GOT HERE onActivated (inside tab)");
  });
});

chrome.tabs.getCurrent(function(tab) {
  tab.onZoomChange.addListener(function(){
    console.log("GOT HERE onZoomChange (inside tab)");
  });
});

// this is actually part of the message passing test
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

当然,这些只是测试,但上述事件都没有真正触发过。变得有点绝望,然后我想'好吧,让我们使用消息传递方法'在用户按下按钮时将消息从contentscript.js发送到background.jscontentscript.js 看起来像这样:

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("just a canary - got here...");

  var btn = document.getElementById("button");
  if (btn) {
    console.log("there is a button!");
  } else {
    console.log("there is NO button!");
  }
  btn.addEventListener("click", function () {
    console.log("clicked the button!!!!");
    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
      console.log(response.farewell);
    });
  })
});

此外,我们永远不会到达这个事件处理程序(但是为什么哦为什么?!这是 DOM 完全加载时的标准 jquery-less 代码)。所以,这就是我想我可以向聚集的专家寻求建议的时候。

TL;DR:我想跟踪 activeTab 上的事件,并且如果给定的 DOM 元素使其外观对其进行操作(通过注入元素)。

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

    默认情况下,Content Script"run_at" 属性为"document_idle",这意味着您的脚本将在window.onload 事件触发后被注入,并且显然晚于DOMContentLoaded 事件。所以实际上你在内容脚本中的代码根本没有被执行。

    要使您的代码正常工作,可以:

    1. 移除外部DOMContentLoaded事件监听器

    2. 或在您的manifest.json 中添加"run_at": "document_start" 部分

    您可以查看run_at 部分以获得更多详细信息。

    【讨论】:

    • 感谢灰原爱,我确实删除了 DOMContentLoaded 事件监听器。使用MutationObserver我终于只需要contentscript.js,不需要background.js进行检测和注入。我会把你的答案标记为正确的。
    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多