【问题标题】:How to fetch the value of a key from localstorage which is stored in your browser in a Chrome Extension如何从本地存储中获取密钥的值,该密钥存储在 Chrome 扩展中的浏览器中
【发布时间】:2020-04-19 04:56:55
【问题描述】:

我是开发 Chrome 扩展程序的新手。

我正在尝试获取存储在浏览器本地存储(检查 -> 应用程序 -> 本地存储)中的其中一个键的值。我想要做的是在我的 Chrome 扩展程序中,当您单击一个按钮时,我只需要它从本地存储中获取在浏览器当前选项卡中打开的页面的值。

这是我正在使用的 JS 函数 -

chrome.storage.local.get(['granted.selected'], function(result) {
            console.log('Value currently is ' + result.granted.selected);
         }); 

granted.selected - 是我要获取其值的键的名称。

执行此操作时,我得到“Value current is undefined”,而我希望它获取存储在上述键 (granted.selected) 中的值。

我需要添加什么才能从我当前打开的选项卡的本地存储中获取该键的值?

简而言之 - 只想从 Chrome 扩展程序访问网页的 localStorage。

任何帮助将不胜感激。谢谢!!

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

    chrome.storage.local 不是localStorage,它是一个完全不同的存储 API。

    localStorage 是一个 DOM 存储。
    要访问网页的 DOM,您需要 content script [1]
    这是弹出脚本或后台脚本中的程序注入示例:

    chrome.tabs.executeScript({
      code: 'localStorage["keyName"]'
    }, ([result] = []) => {
      if (!chrome.runtime.lastError) {
        console.log(result);
        // use the result here inside the callback
      }
    });
    

    注意事项:

    • 您需要 manifest.json 中的权限,如 [1] 中所述。
    • keyName 是在网页的 devtools“应用程序”面板中看到的密钥名称
    • 扩展的每个部分都有其own devtools console

    【讨论】:

    • 不一定需要内容脚本。他只需要访问在窗口对象中可用的本地存储。请在此处了解 developer.mozilla.org/en-US/docs/Web/API/Window/localStorage –
    • 在这种情况下需要内容脚本。扩展有多个上下文,问题清楚地表明 OP 想要访问网页的 localStorage,这只能通过内容脚本实现。
    • 知道了。让我试试这两个选项,看看它是否有效。感谢您的帮助
    猜你喜欢
    • 2013-08-11
    • 2012-01-15
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    相关资源
    最近更新 更多