我有这段代码(感谢Shah Abax Khan),我希望将其设为Chrome扩展程序。我写了一个设置/选项页面,但它实际上并没有保存设置。帮助
使用Javascript:
var pretty_fied = false;
var isOn = localStorage.isOn;
var isCapFirst = localStorage.isCapFirst;
var firstLetterPerWord = localStorage.firstLetterPerWord;
function yay() {
if ($("#on").value == "on") {
isOn = true;
localStorage["isOn"] = true;
}
else {
isOn = false;
localStorage["isOn"] = false;
}
if ($("#first").value == "on") {
isCapFirst = true;
localStorage["isCapFirst"] = true;
}
else {
isCapFirst = false;
localStorage["isCapFirst"] = false;
}
if ($("#per").value == "on") {
firstLetterPerWord = true;
localStorage["firstLetterPerWord"] = true;
}
else {
firstLetterPerWord = false;
localStorage["firstLetterPerWord"] = false;
}
};
$('input, textarea').keyup(function () {
alert(isOn);
if (isOn) {
prev = true;
var value = $(this).val();
var altText = '';
for (num = 0; num < value.length; num++) {
if (num % 2 == 0)
altText += value[num].toUpperCase();
else
altText += value[num].toLowerCase();
}
$(this).val(altText);
}
});
以下是HTML:
<!DOCTYPE html>
<html>
<head>
<title>Y.A.Y | Options</title>
<script type="text/javascript" src="/js/caps.js"></script>
</head>
<body>
<h1>Settings</h1>
<form>
<label>Enabled: </label>
<select id="on">
<option value="on">Yes</option>
<option value="off">No</option>
</select>
</br>
<label>First Letter:</label>
<select id="first">
<option value="on">Capital</option>
<option value="off">Lowercase</option>
</select>
</br>
<label>Change First Letter of Each </label>
<select id="per">
<option value="on">Word</option>
<option value="off">Sentence</option>
</select>
<button id="done" onclick="yay()">Save</button>
</form>
</body>
</html>
yay()应该保存设置,但它没有。
答案 0 :(得分:1)
在Chrome扩展程序中,您不应使用LocalStorage。它适用于网站。
使用Chrome Storage代替:
JavaScript的:
var pretty_fied = false;
var isOn;
var isCapFirst;
var firstLetterPerWord;
getData()
function getData() {
chrome.storage.sync.get( function ( data ) {
isOn = data.isOn;
isCapFirst = data.isCapFirst;
firstLetterPerWord = data.firstLetterPerWord;
} )
}
function yay() {
isOn = $("#on").value == "on";
isCapFirst = $("#first").value == "on";
firstLetterPerWord = $("#per").value == "on";
chrome.storage.sync.set( {
isOn: isOn,
isCapFirst: isCapFirst,
firstLetterPerWord: firstLetterPerWord
} )
}