chrome extension: switching from localstorage to c

2019-09-08 15:15发布

I finally got one of my first JS scripts running as planned in Firefox. Now I need to switch to chrome.storage because it will otherwise not run in my extension.

Basically I want to update a Value in a HTML file, which can be changed by input in a submission box.

You are very welcome to pick around in my code, and tell me what is totally abnormal. But I am quite new to JS, and am simply trying to get this to work. Since this worked with localstorage, I guess I have to get it to work with chrome storage too. Once I get it to work, cleaning this mess can begin. Thank you in advance! (I am trying to solve this since around 12 hours not. Can't grasp it.)

the error i get when examining the script:

Uncaught Error: Invocation of form get(string) doesn't match definition get(optional string or array or object keys, function callback)
    at normalizeArgumentsAndValidate (extensions::schemaUtils:112:11)
    at StorageArea.self.(anonymous function) [as get] (extensions::StorageArea:35:14)
    at chrome-extension://fcbadpjebgjnohhcihmkopdbnbjjmnod/initialize_id.js:5:26

options.html this is the "settings" file where one inputs the id which shall be changeable.

      </head>
  <body>
    <p>ENTER YOUR ID FROM tsindex.com BELOW</p>
      <form>
          <input id="ts_id_js_html" type="text" value="128856"></input>
          <br>
          <br>
          <button onclick="store()">Save/Load</button>
      </form> 

<script src="initialize_id.js"></script>
<script src="options.js"></script>
<script src="load_id.js"></script>
  </body>
</html>

options.js this stores the given ID from the input field in chrome.storage.local (before localstorage)

function store(){
 var input_id = document.getElementById("ts_id_js_html").value;
 chrome.storage.local.set("ts_id_js", input_id);
}

initialize.js if chrome.storage.local is undefined executes X once. else it gets the stored value and replaces the input in the filed.

var init_count;

if (chrome.storage.local.get("ts_id_js") === undefined && init_count == undefined) {
    init_count++; //ignore this for now
} else {
    document.getElementById("ts_id_js_html").value = chrome.storage.local.get("ts_id_js");
}

load_id_to_popup.js this gets loaded when the popup.html gets opened, and inputs the given ID in the necessary field.

 document.getElementById('input_id').dataset.serverid =
 chrome.storage.local.get("ts_id_js");

IGNORE ! load_id.js THIS IS CURRENTLY REDUNDANT, ignore this.

 document.getElementById("ts_id_js_html").value =
 chrome.storage.local.get("ts_id_js");

1条回答
三岁会撩人
2楼-- · 2019-09-08 16:02

chrome.storage.local.get is asynchronous, it is mean, Chrome returns value to callback function:

chrome.storage.local.get("ts_id_js", function(obj) {
    let value = obj["ts_id_js"];
});
查看更多
登录 后发表回答