Javascript 在popup.html浏览器扩展中保存用户首选项
我已经完成了Chrome扩展的主要功能的开发,但是我很难在popup.html文件中保留用户的首选项。因此,我在popup.html文件中有一个按钮,它应该是用户的首选项,但在重新加载页面并再次单击扩展名时,我无法保留用户的首选项 我尝试使用Chrome存储API,但无法实现我想要的。 以下是popup.html的图片: 我希望能够保存用户的偏好,如果他们选择开关之间切换。但就我现在所知,当用户将其滑上(如图所示)时,在单击弹出窗口并再次单击图标时,按钮始终默认为“关闭”位置 我尝试使用localStorage和Chrome Storage API的组合来加载用户首选项,但无法做到这一点 这是我的popup.js文件:Javascript 在popup.html浏览器扩展中保存用户首选项,javascript,html,google-chrome,google-chrome-extension,Javascript,Html,Google Chrome,Google Chrome Extension,我已经完成了Chrome扩展的主要功能的开发,但是我很难在popup.html文件中保留用户的首选项。因此,我在popup.html文件中有一个按钮,它应该是用户的首选项,但在重新加载页面并再次单击扩展名时,我无法保留用户的首选项 我尝试使用Chrome存储API,但无法实现我想要的。 以下是popup.html的图片: 我希望能够保存用户的偏好,如果他们选择开关之间切换。但就我现在所知,当用户将其滑上(如图所示)时,在单击弹出窗口并再次单击图标时,按钮始终默认为“关闭”位置 我尝试使用loc
function saveChanges() {
// Get a value.
if ($('#myonoffswitch').is(':checked')) {
localStorage.mydata = 'y';
} else {
localStorage.mydata = 'n';
}
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({
'value': localStorage.mydata
}, function () {
});
}
$(document).ready(function () {
if (localStorage.getItem('mydata')) {
if (localStorage.mydata == 'n') {
$('myonoffswitch').attr('checked', false);
} else {
$('myonoffswitch').attr('checked', true);
}
} else {
if ($('#myonoffswitch').is(':checked')) {
localStorage.setItem('mydata', 'y');
} else {
localStorage.setItem('mydata', 'n');
}
}
$('#myonoffswitch').click(function () {
saveChanges();
});
});
这是我的popup.html文件:
<html>
<head>
<title>Replace some text</title>
<link rel="stylesheet" type="text/css" href="popup.css">
<script type='text/javascript' src='jquery-1.12.3.js'></script>
<script type="text/javascript" src="options.js"></script>
</head>
<body>
<div>
<div class='logo'>
</div>
<div class='main-text'>
</div>
<div class='buttons-area'>
<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch">
<label class="onoffswitch-label" for="myonoffswitch"></label>
</div>
<div class='block-spoilers-message'>
On Off Button
</div>
</div>
</div>
</body>
</html>
因此,简而言之,我需要保留popup.html上的设置,并在内容脚本中使用这些设置来确定是否运行主要部分。
我已经研究了其他StackOverflow解决方案,但没有任何一个能够正常工作。
如果您能帮助解决此问题,我们将不胜感激
.
中的$('myonoffswitch').attr('checked',true)代码>
您的webextension需要存储
权限。看
投票以打字错误结束。您刚刚忘记了.
中的$('myonoffswitch').attr('checked',true)代码>我最近编写了一个模块来管理选项:。表单还将自动与保存的选项同步
$(document).ready(function () {
var on_off_pref = true;
chrome.storage.onChanged.addListener(function (changes, namespace) {
for (key in changes) {
var storageChange = changes[key];
on_off_pref = storageChange.newValue;
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
});
if (on_off_pref === 'y') {
//Execute main functionality here only if the button in popup.html is on.
}
});