我正在编写一个简单的铬扩展名,其中包含一个带有关联popup.js
文件的HTML (popup.js
)。当用户单击popup.js
中的按钮时,我希望使用chrome.storage.local.get
和chrome.storage.local.set
检索和设置一个值。在这个过程之后,我想通知用户更新已经完成(使用一些简单的jQuery)。但是,我将这个jQuery更新代码放在chrome.storage.local.set
的回调中,当单击按钮时,动态更新永远不会发生,因此,我怀疑回调从未执行过。我认为这是因为我将通知片段放置在chrome.storage.local.get
回调中,并且能够显示正确的消息:
popup.html
<html>
<head>
<title>Test Extensio</title>
<script src='jquery.min.js'></script>
<script src='popup.js'></script>
</head>
<body>
<button class='get-notified'>Run Test</button>
<div class='update-display'></div>
</body>
</html>
popup.js
$(document).ready(function(){
$('body').on('click', '.get-notified', function(){
chrome.storage.local.get(['counter'], function(result){
var new_count = result.counter === undefined ? 1 : parseInt(result.counter)+1
chrome.storage.local.set({'counter':new_count}, function(){
$('.update-display').html(`The count is: ${new_count}`)
//this is never executed
});
});
});
});
使用上面的代码示例,永远不会显示计数器消息。但是,当我移除chrome.storage.local.set
并在chrome.storage.local.get
回调中运行更新时,它确实工作了:
chrome.storage.local.get(['counter'], function(result){
var new_count = result.counter === undefined ? 1 : parseInt(result.counter)+1
$('.update-display').html(`The count is: ${new_count}`)
//this works
});
为什么$('.update-display').html(...)
工作在第一个回调,chrome.storage.local.get
的回调,而不是chrome.storage.local.set
的内部回调。
我的manifest.json
文件:
{
"manifest_version": 2,
"name": "Test extension",
"description": "A Description coming soon",
"version": "2.0",
"browser_action": {
"default_icon": "/images/icon.png",
"default_popup": "popup.html"
},
"background" : {
"scripts" : ["jquery.min.js", "popup.js"]
},
"permissions": [
"storage",
"activeTab",
"declarativeContent",
"webNavigation",
"unlimitedStorage",
"tabs",
"cookies",
"webRequest",
"webRequestBlocking",
"http://*/",
"https://*/",
"http://fonts.googleapis.com/",
"https://fonts.googleapis.com/"
],
"web_accessible_resources": ["popup.html"],
....
}
有人知道为什么会发生这种令人困惑的行为吗?非常感谢!
发布于 2020-06-19 19:58:43
对于那些感兴趣的人,我发现了这个问题:我在我的chrome.storage.local.get
之上添加了一个chrome.storage.local.get
,这将不可避免地关闭弹出窗口,在用户单击该按钮一定次数之后。我只需将window.close
移到原始回调中,chrome.storage.local.set
就能正常工作:
/*this did not work
if (somecondition){
window.close();
}
*/
chrome.storage.local.get(['counter'], function(result){
var new_count = result.counter === undefined ? 1 : parseInt(result.counter)+1
chrome.storage.local.set({'counter':new_count}, function(){
$('.update-display').html(`The count is: ${new_count}`)
//this worked
if (somecondition){
window.close();
}
});
});
https://stackoverflow.com/questions/62477411
复制相似问题