【发布时间】: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.js。 contentscript.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