javascript - 后台脚本中的 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
吗?
解决方案
请试试这个,告诉我它是怎么回事:
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"
});
}
})
推荐阅读
- bash - 编写一个 shell 脚本,该脚本将返回您的存储库 git 跳过的文件列表
- embedded - STM32 上的 Eigen 只能工作到一定大小
- matlab - griddata 在所需区域之外生成数据
- javascript - 即使有结果,Promise 也会返回未定义的值
- android - 进程'命令'NDK PATH'以非零退出值2完成
- c++ - 计算字符串 S 中所有数字出现的次数。?
- sql - 在sql表中查找重复的列值对
- php - 按日期选择最新行并按客户端 ID 分组(MySQL)
- php - 在所有 php 页面中应用会话重新生成 ID 是否安全?
- javascript - 中间件替换内置 Express.js 函数有什么意义?