我不确定如何正确提出这个问题,因为很难解释,所以我将使用一个例子。
我想做的是弄清楚如何使用将与当前选项卡交互的 Chrome 扩展程序的 popup.html 内部的链接来激活类似书签之类的东西。
例如:如果您单击 chrome 扩展程序图标,则会出现一个弹出窗口(通常的下拉窗口)。在该窗口中会有一个增加图像大小的按钮(就像书签栏的书签)。
我想要的是该按钮与当前打开的选项卡而不是 popup.html 页面进行交互。
我在 list 以及正在定义的脚本中拥有适当的权限(所有网址和选项卡)。那里一切测试都正常。但我知道我的解决方案(不起作用)可能离目标很远,而且我现在可能还没有接近目标。所以我在这里寻求帮助。
背景.js
function zii() {
function zoomImage(image, amt) {
if (image.initialHeight == null) { /* avoid accumulating integer-rounding error */
image.initialHeight = image.height;
image.initialWidth = image.width;
image.scalingFactor = 1;
}
image.scalingFactor *= amt;
image.width = image.scalingFactor * image.initialWidth;
image.height = image.scalingFactor * image.initialHeight;
}
var i, L = document.images.length;
for (i = 0; i < L; ++i) zoomImage(document.images[i], 2);
if (!L) alert("This page contains no images.");
}
popup.html
<button onClick="zii()">Test</button>
后台功能也链接在 popup.html 页面内部。实际的 popup.html 页面非常大,因此我在这里仅展示了它的基础知识,而没有包含与扩展的其他方面相关的所有相关代码。
我显然不知道我做错了什么,或者我正在尝试的事情是否可能。
目标摘要: 简而言之,我只想单击 popup.html 中的按钮并增加当前打开的选项卡上图像的大小(与使用书签执行此操作的方式相同)。
最佳答案
首先,我建议阅读 extensions architecture .
如果您想通过单击弹出窗口中的按钮在当前窗口中注入(inject) .js 文件或某些代码,您可以简单地使用 chrome.tabs.executeScript
来执行此操作在按钮 onclick 处理程序中,同时传递 null
作为第一个 tabId
参数,因为它默认为当前窗口的事件选项卡。
例如:
chrome.tabs.executeScript(null, {
code: "console.log('Injected.')"
});
或者:
chrome.tabs.executeScript(null, {
file: "content.js"
});
请务必在您的 manifest.json
权限中拥有 “activeTab”
。
关于javascript - Chrome 扩展 - 激活当前选项卡的 popup.html 中的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50322559/