chrome.runtime.lastError is coming as 'UNDEFINED' despite of fetching an unset variable from chrome local storage,

守給你的承諾、 提交于 2019-12-13 01:28:58

问题


I am trying to check if the key, value pair has been set in the chrome.storage.local. for that i took the help of a similar kind of problem here. Here the variable i'm trying to get from storage has not been set by me. When i try to catch the error using lastError. It is coming as undefined, whereas it was suppose to defined and set due to error in reading a variable that has not been set previously ( as per what i googled). Please help me to detect the error while reading a variable that has not been set.

manifest.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://*/*"]
}

background.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>

回答1:


Non-existence of the value is not an API error, hence chrome.runtime.lastError is not set.

If you want to know whether the variable is set or not, check the results:

chrome.storage.local.get('testVar1', function(result) {
    if (result.testVar1 === undefined) {
        alert('Var not set');
        return;
    }
    // Rest of code...
});


来源:https://stackoverflow.com/questions/18673374/chrome-runtime-lasterror-is-coming-as-undefined-despite-of-fetching-an-unset-v

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!