简体   繁体   中英

How to set value in localStorage of webView

I am connecting to url which loads only if token value is set properly to my webView browser.

This is a script where null value of userToken is found when I start my webView:

$.ajaxSetup({
    data: {
        token: localStorage.userToken
    }
});

sendToApp = function(_key, _val) {
    var iframe = document.createElement("IFRAME");
    iframe.setAttribute("src", _key + ":##sendToApp##" + _val);
    document.documentElement.appendChild(iframe);
    iframe.parentNode.removeChild(iframe);iframe = null;
}

IsMobile = true;

$.when(

    loadData.setup()

).then(function(data) {

    Setup = data;

    Struct = new App.Collection.Struct();
    View = new App.View.Phone();
    Zone = new App.Collection.Zone();

    Zone.setAll();
    Zone.findWhere({id:"0"}).set('path', 'Favourites')
    Struct.startLoop();
});

I receive error:

I/chromium: [INFO:CONSOLE(3)] "Uncaught TypeError: Cannot read property 'userToken' of null" , source: http://217.76.112.72:60180/js/mobile.js (3)

How can I set userToken to local storage of my android webView so this value won't be null anymore?

I read few threads about webView database or javascript parameters setting but I can't find answer to my question:

JS property setting:

Uncaught TypeError: Cannot set property 'value' of > null" in Android

Database topic:

Android webview & localStorage

Using local storage on Android webview

For example in those topics people are setting path to some kind of database which from what I understood is localStorage but if am I right how can I set value to it?

Edit: my webView setup:

public void setupWebView(String url, String token) {
    HashMap<String, String> map = new HashMap<>();
    map.put("userToken", token);

    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url, map);
}

Using the 2 parameter loadUrl won't help. You won't be able to access the headers.

What you CAN do, is you can call a function in your WebView.

webView.loadUrl("javascript:setUserToken(token)");

You can use this function to launch the rest of your code on the page too.

function setUserToken(userToken) {
    $.ajaxSetup({
        data: {
            token: userToken
        }
    });

    // ... Launch your ajax
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM