首页 > 解决方案 > 后台脚本中的 if/else 不会在扩展单击时执行,但仅在解压缩扩展刷新后执行

问题描述

我正在尝试加载包含 if/else 语句的后台脚本 (extension-starter.js)。我将用户对如何在本地存储中打开扩展程序(弹出窗口、新窗口、新选项卡)的偏好存储。打开扩展程序后,我希望它能够检索保存的值并适当地打开扩展程序,但由于某种原因,在更改首选项(例如从弹出窗口到新选项卡)时,单击扩展程序图标会以先前状态打开扩展程序。只有在我刷新解压缩的扩展程序后,它才会按预期打开应用程序。

    // Here is the manifest.json...(took out unnecessary info)
    {
    "manifest_version": 2,
    "background": {
    "persistent": false,
    "scripts": ["extension-starter.js"]
    },
    "browser_action": {}
}
    // Here is the extension-starter.js...
    const extPrefer = localStorage.getItem('extensionPreference');

    if (extPrefer === null) {
    localStorage.setItem('extensionPreference', 'popup');
    }

    chrome.browserAction.onClicked.addListener(function () {
    if (extPrefer === 'window') {
        chrome.windows.create({url: chrome.runtime.getURL("index.html"), width: 500, height: 600});
    }
    else if (extPrefer === 'tab') {
        chrome.tabs.create({url:chrome.extension.getURL("index.html")});
    }
    else {
    chrome.browserAction.setPopup({
        popup: "index.html"
    });
    }
    })

我希望从本地存储中检索保存的首选项并以所需的方式打开扩展。


更新 上述问题是由chrome.browserAction.setPopup({popup: "index.html"});. 执行setPopup后,我无法更新回窗口或选项卡首选项。似乎setPopup是在清单上设置的,并且在将首选项从弹出窗口更改为选项卡或窗口时无法覆盖。

更新的问题: 1.有没有办法做相反的事情setPopup?2.还有其他方法setPopup吗?

标签: javascriptgoogle-chromemanifest

解决方案


请试试这个,告诉我它是怎么回事:

    if (localStorage.getItem('extensionPreference') === null) {
        localStorage.setItem('extensionPreference', 'popup');
    }

    chrome.browserAction.onClicked.addListener(function () {
        // move this inside the click function
        const extPrefer = localStorage.getItem('extensionPreference');

        if (extPrefer === 'window') {
            chrome.windows.create({ url: chrome.runtime.getURL("index.html"), width: 500, height: 600 });
        }
        else if (extPrefer === 'tab') {
            chrome.tabs.create({ url: chrome.extension.getURL("index.html") });
        }
        else {
            chrome.browserAction.setPopup({
                popup: "index.html"
            });
        }
    })

推荐阅读