Discussions » Development

Help with async/await of GM.getValue/GM.setValue

§
Posted: 18.03.2024
Edited: 18.03.2024

Greetings!

I am attempting to make a command menu which text depends on a current given value.

I fail to get values. Please help.

(async function registerMenuCommand(){
  try {
    for (let key in proxy) {
      keyValue = await GM.getValue(key, true)
      if (keyValue) {
        let status = 'Disable';
        let value = false;
      } else {
        let status = 'Enable';
        let value = true;
      }
      await GM.registerMenuCommand(`${status} instance ${key}`, () => toggleStatus(key, value));
    }
    for (let key of ['clearnet', 'i2p', 'loki', 'tor', 'yggdrasil']) {
      keyValue = await GM.getValue(key, true)
      if (keyValue) {
        let status = 'Disable';
        let value = false;
      } else {
        let status = 'Enable'
        let value = true;
      }
      await GM.registerMenuCommand(`${status} telecom system ${key}`, () => toggleStatus(key, value), key[0]);
    }
  } catch (err) {
    console.warn(err)
    console.info('API GM.registerMenuCommand does not seem to be available.')
  }
})();

async function toggleStatus(key, value) {
  await GM.setValue(key, value)
  alert(`${key} is now ${status}`)
}

From https://greasyfork.org/en/scripts/465936-proxy-redirect

§
Posted: 19.03.2024

Solved by declaring vars outside of statement if and inside loop for.

(async function registerMenuCommand(){
  try {
    for (let key in proxy) {
      let keyValue = await GM.getValue(key, true)
      let status, value;
      if (keyValue) {
        status = 'Disable';
        value = false;
      } else {
        status = 'Enable';
        value = true;
      }
      await GM.registerMenuCommand(`${status} instance ${key}`, () => toggleStatus(key, value, status));
    }
    for (let key of ['Clearnet', 'DHTTP', 'I2P', 'Loki', 'Tor', 'Veilid', 'Yggdrasil']) {
      let keyValue = await GM.getValue(key, true)
      let status, value;
      if (keyValue) {
        status = 'Disable';
        value = false;
      } else {
        status = 'Enable'
        value = true;
      }
      await GM.registerMenuCommand(`${status} telecom system ${key}`, () => toggleStatus(key, value, status), key[0]);
    }
  } catch (err) {
    console.warn(err)
    console.info('API GM.registerMenuCommand does not seem to be available.')
  }
})();

async function toggleStatus(key, value, status) {
  await GM.setValue(key, value)
  //alert(`${key} is now ${status}d`)
  //location.reload();
}
§
Posted: 19.03.2024
Edited: 19.03.2024

Master it here: https://www.freecodecamp.org/news/scope-in-javascript-global-vs-local-vs-block-scope/

In the past, we used "var" to declare which is not good. ("var" is always global)

Now we have "let" and "const" to declare the variables correctly. You need to think about the scope of variables.

§
Posted: 26.03.2024

Thank you CY Fung!

Post reply

Sign in to post a reply.