1

我正在尝试检查键值对是否已在 chrome.storage.local 中设置。为此,我在这里得到了类似问题的帮助。在这里,我试图从存储中获取的变量尚未由我设置。当我尝试使用lastError捕获错误时。它是未定义的,而由于读取以前未设置的变量时出错(根据我搜索的内容),它应该被定义和设置。请帮助我在读取尚未设置的变量时检测错误。

清单.json

{
    "name": "TestExtension",
    "version": "1.0",
    "manifest_version": 2,
    "background": {
        "scripts": ["jquery.js", "background.js"]
    },

    "description": "Test the extension features here",
    "icons": {
        "16": "images/16x16.png",
        "48": "images/48x48.png",
        "128": "images/128x128.png"
    },

    "page_action": {
        "default_icon": {
            "19": "images/19x19.png",
            "38": "images/38x38.png"
        },
        "default_title": "Test Plugin default title",
        "default_popup": "popup.html"
    },

    "permissions": ["tabs", "storage", "http://*/*", "https://*/*"]
}

背景.js

function showTheExtension(tabId, changeInfo, tab) {
    console.log("Extension loaded");
    chrome.pageAction.show(tabId);
} // ---EOF checkForValidUrl---
chrome.tabs.onUpdated.addListener(showTheExtension);

popup.js

$('document').ready(function() {
    chrome.storage.local.get('testVar1', function(result) {
        if (chrome.runtime.lastError) {
            alert('Var not set')
        }
        console.log(result);
        console.log(chrome.runtime.lastError.message);
    });
});

popup.html

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
   <h3>Welcome to the test project for designing chrome plugins</h3>

<script type="application/x-javascript" src="./jquery.js"></script>
<script type="application/x-javascript" src="./popup.js"></script>
</script>
</body>
</html>
4

1 回答 1

5

该值不存在不是 API 错误,因此chrome.runtime.lastError未设置。

如果您想知道是否设置了变量,请检查结果:

chrome.storage.local.get('testVar1', function(result) {
    if (result.testVar1 === undefined) {
        alert('Var not set');
        return;
    }
    // Rest of code...
});
于 2013-09-07T15:20:20.717 回答