Chrome 扩展 - 为当前选项卡激活 popup.html 中的脚本

Chrome Extension - Activating a script within the popup.html for the current tab

我不确定如何正确地提出这个问题,因为它很难解释,所以我会举个例子。

我想做的是弄清楚如何使用 chrome 扩展的 popup.html 内部的 link 来激活像小书签这样的东西,它将与当前的选项卡

例如:如果您点击 chrome 扩展程序图标,将出现一个弹出窗口(通常是下拉 window)。在那个 window 中,可以说是一个增加图像大小的按钮(就像书签栏的小书签一样)。

我想要的是让该按钮与当前打开的选项卡而不是 popup.html 页面进行交互。

我在清单以及正在定义的脚本中拥有适当的权限(所有 url 和选项卡)。那里的一切都测试正常。但我知道我的解决方案(不工作)可能偏离目标,我什至可能在这一点上还差得远。所以我在这里寻求帮助。

background.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 页面内 linked。实际的 popup.html 页面非常大,所以我在这里只展示了它的基础知识,而没有包括与扩展的其他方面相关的所有相关代码。

我显然不知道我做错了什么,或者我的尝试是否可行。

Objective总结: 简而言之,我只想单击 popup.html 中的按钮并增加当前打开的选项卡上的图像大小(与使用书签一样)。

首先,我建议阅读 extensions architecture

如果您想通过单击弹出窗口中的按钮在当前 window 中注入 .js 文件或某些代码,您只需在按钮 onclick 处理程序中使用 chrome.tabs.executeScript 即可将 null 作为第一个 tabId 参数传递,因为它默认为当前 window.

的活动选项卡

例如:

chrome.tabs.executeScript(null, {
    code: "console.log('Injected.')"
});

或:

chrome.tabs.executeScript(null, {
    file: "content.js"
});

确保您的 manifest.json 权限中也有 "activeTab"