0

I'm trying to simply log on to a webapi. Once fetch successful, it gives me bearer token, username, etc..

And then simply store those values in a variable and then username on the popup.

But when I click on the button, it doesn't wait for the fetch call to succeed and sets page variable before that which turns to be shown value as undefined or blank.

Subsequently on 3rd or 4th try on clicking the login button it's successful and display's the username.

Also once the popup is closed those values are gone. How can I store token and other info to use it for subsequent next fetch calls.

    var respjson = "";
var token = "";
document.getElementById('btnLogin').onclick = function () {
    var robject = "";
    robject = Login();
    setTimeout(
        function () {
            //do something special
            if (robject == '0' || robject == '' || robject == 'undefined' || robject == null) {
                console.log("var not set: " + robject);
            }
            else {
                console.log(robject);
                $("#lbluname").html('<p>Set UName</p>');
                $("#lbluname").html('<p>' + robject.userName + '</p>');
                $("#lblToken").html('<p>Set Token</p>');
                $("#lblToken").html('<p>' + token + '</p>');
            }
        }, 5000);
};

function Login() {
    var credentials = {
        "username": $("#txtUName").val(),"password": $("#txtPass").val()
    }
    console.log(credentials);
    chrome.runtime.sendMessage({ greeting: "Login", cred: credentials },
        function (response) {
            respjson = JSON.parse(response.farewell);
            token = respjson.access_token;
        });
    return respjson;
}
Hesoti
  • 57
  • 8

0 Answers0