Currently, I am in the process of developing a Chrome extension that utilizes a content script to make modifications on specific sections of a website. Everything was functioning smoothly until I decided to incorporate an options page into my extension.
My approach involves using an options.html file to store user preferences in local storage, as showcased below:
<html>
<head><title>Options</title></head>
<script type="text/javascript">
function save_options() {
var select = document.getElementById("width");
var width = select.children[select.selectedIndex].value;
localStorage["site_width"] = width;
}
function restore_options() {
var fwidth = localStorage["site_width"];
if (!fwidth) {
return;
}
var select = document.getElementById("width");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == fwidth) {
child.selected = "true";
break;
}
}
}
</script>
<body onload="restore_options()">
Width:
<select id="width">
<option value="100%">100%</option>
<option value="90%">90%</option>
<option value="80%">80%</option>
<option value="70%">70%</option>
</select>
<br>
<button onclick="save_options()">Save</button>
</body>
</html>
In addition to the options.html file, there is also a background.html file responsible for managing communication between the content script and local storage:
<html>
<script type="text/javascript">
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "siteWidth")
sendResponse({status: localStorage["site_width"]});
else
sendResponse({});
});
</script>
</html>
Lastly, there is the actual content script which appears as follows:
var Width;
chrome.extension.sendRequest({method: "siteWidth"}, function(response) {
width = response.status;
});
Unfortunately, none of this code seems to be effective. While it appears logically sound to me, my limited programming experience might have overlooked some crucial details.
Could someone please provide a simplified explanation of how local storage works?