【问题标题】:how to get [chrome.instanceID.getID] , [chrome.storage.sync.get] by async & await?如何通过 async & await 获取 [chrome.instanceID.getID] 、 [chrome.storage.sync.get]?
【发布时间】:2022-04-17 21:16:39
【问题描述】:

如何使用 async 和 await 获取 Chrome 扩展程序的信息?

[chrome.instanceID.getID]
[chrome.storage.sync.get]

我们试过这段代码:

async function test()
{
let _r = await chrome.instanceID.getID();
return _r;
}
let _pc_id = test();

但是_pc_id 返回一个承诺。我们没有办法获得其中的价值。我们应该怎么做?

【问题讨论】:

  • 您好,您找到解决方案了吗?
  • 还没有 :( 我的临时解决方案是:在“chrome.runtime.onInstalled”中创建一个 ID-byTiming 作为设备 ID。

标签: google-chrome-extension async-await es6-promise chrome-extension-manifest-v3


【解决方案1】:

您可以像这样获取 instanceID,但不能将其存储在变量中以在承诺范围之外使用它,AFAIK。您可能想阅读以下内容:saving data from promise in a variable

如果你想使用Promise的返回值你需要在promise中或者在promise之后的.then()s中做,至少我是这样做的。

chrome.instanceID.getID 示例:

chrome.instanceID.getID((instance_id) => {
    console.log(instance_id);
    // Execute your other related code here
});

var promise = chrome.instanceID.getID();
promise.then((instance_id) => {
    console.log(instance_id);
    // Execute your other related code here
});

chrome.instanceID.getID()
.then((instance_id) => {
    console.log(instance_id);
    // Execute your other related code here
});

chrome.storage.sync.get 示例:

chrome.storage.sync.get('myKey', function(items) {
    var key = items.myKey;
    // Below code is an example, change it to your needs
    if (key) {
        console.log(key)
    } else {
        key = createKey();    // a custom function that generates keys
        chrome.storage.sync.set({myKey: key}, function () {
            console.log(key);
        });
    }
};

【讨论】:

    猜你喜欢
    • 2020-03-06
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多