Chrome扩展:Can't从chrome.local变量中检索值

Chrome Extension: Can't retrieve values from chrome.local variables

本文关键字:local chrome 变量 检索 扩展 Can Chrome      更新时间:2023-09-26

我正在pop.js中设置chrome.local变量,但无法在content.js 中检索它们

popup.js

chrome.storage.local.set('TITLE',title);

content.js

var title = null;
    $(".class").each(function () {
          chrome.storage.local.get('TITLE', function (result) {
                                    title = result.TITLE;
                    console.log('inside'+title);//prints value
                                });

    }
  console.log(title);//returns null;

返回title作为null

Chrome控制台输出为:

outside: null
content.js:42 insideJava: A Beginner's Guide, Sixth Edition

chrome.storage.local.get是一个异步调用,这意味着当您调用console.log(title);时,chrome.storage.local.get的回调尚未执行,那么title仍然是null。你应该把你的逻辑放在回调中。