How to store value in a string object and display that element on another page?

Asked

Viewed 158 times

0

My job myFunction picks up the elements username and password typed,and sends these values storing in a global variable to the next page.

My job tToken authenticate this information and play to next page the valid Token for me to manipulate.

The problem is that I am not able to do or think of a way to play the login and password typed in the field for the next pages dynamically. Then I managed to do this but it works only on the LOGIN page, it displays the filled object only on the login page. When the login is done and authenticated, after updating the page everything disappears, exactly for being stored in variables the values I want. How to do this, other than by variables?

var globalcredential =  "/v1/credentials";
var globalauth = "/v1/auth";
var userlogin = new String();
var passwordlogin = new String();

function myFunction(){
       var userElement = document.getElementsByName('username');
       var passwordElement = document.getElementsByName('password');
       userlogin = $(userElement).val().toString();
       passwordlogin = $(passwordElement).val().toString();
    };



function auth(){

var account = {
        grant_type: "password",
        login : userlogin,
        senha : passwordlogin
    };

    var jsonAccount = JSON.stringify(account);

    console.log(jsonAccount);
    $.ajax({
                  type: "POST" 
                , method : "POST"
                , url : globalauth
                , contentType : "application/json"
                , dataType : "json"
                , data: jsonAccount
                ,success : function(data){
                    console.log("oi");

                },beforeSend : function(request){
                request.setRequestHeader('Content-Type', 'application/json');
        },
        }).done(function(response, status){
          console.log(response,status);     
        }).fail(function(error){
          console.log(error);
        }).always(function(response, status){
        });
}

var classname = document.getElementsByClassName("buttonlogin");

 Array.from(classname).forEach(function(element) {
          element.addEventListener('click', myFunction);
                  element.addEventListener('click', auth);
      });
  • It’s a bit confusing. You’re authenticating via Ajax and want to redirect to another page?

  • As far as I can tell, you don’t want to send password via client-side because the confidentiality and security of this falls below zero. Perhaps storing in a SESSION is safer and more viable.

  • I want to return the user and password, but this user and password cannot be inline in the code. It has to be dynamic.

2 answers

0

You can use the window.localStorage object (see more in https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) With it you will be able to store information on one page and recover on another, since it stores the information in the browser.

Incrementing your code:

function myFunction(){
   var userElement = document.getElementsByName('username');
   var passwordElement = document.getElementsByName('password');
   userlogin = $(userElement).val().toString();
   passwordlogin = $(passwordElement).val().toString();

   // armazenar o usuário
   window.localStorage.setItem('usuario', userLogin);

};

On a subsequent page, it will be possible to get the user with the instruction:

var usuario = window.localStorage.getItem('usuario');

When you need to remove the item, use:

window.localStorage.removeItem('usuario')

But be careful with the storage of sensitive information (such as passwords) in the browser, they can be accessed by another page! The best is to store with some encryption. The most common authentication mechanisms in the various languages do not require you to send the password to each request, so it is interesting not to store it! Usually for subsequent requests, after logging in, a server-generated session number, or encrypted tokens, such as in JWT.

  • That I already do, however to pass a tokenVoce needs user and password.

  • Wouldn’t it be the case that you only store the token then? And referring it to subsequent queries depends on how the server is implemented, if it was implemented by you, you should work that way. If not, In the code snippet Success : Function(data){ console.log("hi"); } ; In this return callback of ajax you have the return of the server, I suppose you have the token, in addition to the login and password you sent, you can store everything in localStorage if you want right now.

  • I understood Vinicius, however to store the token I need to provide a login and password. var Account = { grant_type: "password", login : "", password : "" }; The idea is for me to capture that login and password typed in some input dynamically and store it so I can get the token normally after that.

  • If within that function myFunction you can already get the user and password, and at that point you store in localStorage, you can get the localStorage information later when you want, with window.localStorage.getItem, even if the screen refresh. In short: in myFunction() you define the variables in localStorage, and in the auth() function, you get them, to mount the Account object and make your authentication request.

  • I already managed to do the problem and that in the localstorage I can not bring the information to other servers, and in the question there, I am doing it in an extension.

  • Where do you have "Chrome.storage.local.get('login', Function (result) { b = result.login; console.log(b); } " Is this "console.log(b)" showing something ? I see that you are giving a "Chrome.storage.local.get('password', Function(result){" , and you are using the same name in the result variable, change this name p/ view ...

Show 1 more comment

0


The idea would be an extension to assist an Angular system, where I pull information from a server x and use this information to optimize automatic logins in z v y urls.

I used a specific function of google.Storage documentation that would be slightly different from localstorage https://developer.chrome.com/extensions/storage With localstorage it would not be possible, because as you already say is local, I could not use it to authenticate and provide the token to pull the logins and passwords stored on a server to automatically access the z v y urls.

Example of GET :

   tToken(function(d){
            $.ajax({
                  type: "GET"
                , method : "GET"
                , url : globalauth
                , contentType : "application/json"
                , dataType : "json"
                , Authorization : "Bearer" + d

Below is just the function that captures dynamically what is typed authenticates the token to later perform a GET ajax of this information to pull the data from the database.

 function tToken(callback){
    var b;
    var a;
    chrome.storage.local.get('login', function (result) {
              b = result.login;
              console.log(b); 
          chrome.storage.local.get('password', function (result) {
              a = result.password; 

  var account = {
            grant_type: "password",
            login : b,
            senha : a
        };

  var jsonAccount = JSON.stringify(account);
  console.log(jsonAccount);
        $.ajax({
                      type: "POST" 
                    , method : "POST"
                    , url : globalext
                    , contentType : "application/json"
                    , dataType : "json"
                    , data: jsonAccount
                    ,success: function(data){
                        var obs1 = JSON.stringify(data);
                        var newa = JSON.parse(obs1);  
                        var key = newa.data["token"];
                        callback(key);
                    },beforeSend : function(request){
                    request.setRequestHeader('Content-Type', 'application/json');                   },
    }).done(function(response, status){
    }).fail(function(error){
      console.log(error);
    }).always(function(response, status){
    });
    });
    });
  }

function save(){
    var userElement = document.getElementsByName('username');
    var passwordElement = document.getElementsByName('password');
    var channels = $(userElement).val();
    var keywords = $(passwordElement).val();

    chrome.storage.local.set({'login': channels});
    chrome.storage.local.set({'password': keywords});
    console.log(keywords);
    console.log(channels);
}


var classname = document.getElementsByClassName("buttonlogin");

 Array.from(classname).forEach(function(element) {
           element.addEventListener('click', save);
      });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.