URL with parameter in WebView not working in Android?

前端 未结 8 1448
南笙
南笙 2020-12-20 14:40

I am trying to call the loadUrl method in a webview with the below url

http://stage.realtylog.net/iPhone/functions.php?username=xxx&ID=xxx&act=readFileAndPri

8条回答
  •  轮回少年
    2020-12-20 15:20

    I managed to pass variables in a different way.

    My problem was that anytime I switched to another app, when coming to the webapp, the webview kept reloading. I guess that's because of the following line in my onCreate() method: myWebView.loadUrl(url); I had the idea to pass these state variables in the url, but as you know it is not possible yet. What I did was to save the state of some variables using onSaveInstanceState(Bundle outState) {...} and restore them with onRestoreInstanceState(Bundle savedInstanceState){...}.

    In onCreate method after setting up myWebView I did the following:

    myWebView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String urlString)
    {
         Log.i("onPageFinished", "loadVariables("+newURL+")");
         if(newURL!="")
             myWebView.loadUrl("javascript:loadVariables("+"\""+newURL+"\")");
    }
    
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
    });
    
    jsInterface = new JSInterface(this,myWebView);
    myWebView.addJavascriptInterface(jsInterface, "Android");
    
    if (savedInstanceState != null)
    {
    // retrieve saved variables and build a new URL
    newURL = "www.yoururl.com";
    newURL +="?var1=" + savedInstanceState.getInt("key1");
    newURL +="?var2=" + savedInstanceState.getInt("key2");
    Log.i("myWebApp","NEW URL = " + newURL);
    }
    myWebView.loadUrl("www.yoururl.com");
    

    So, what it happens is that first I load the page and then I pass the variables when the page finished to load. In javascript loadVariables function looks like this:

    function loadVariables(urlString){
        // if it is not the default URL
        if(urlString!="www.yoururl.com")
        {
            console.log("loadVariables: " + urlString);
            // parse the URL using a javascript url parser (here I use purl.js)
            var source = $.url(urlString).attr('source');
            var query = $.url(urlString).attr('query');  
            console.log("URL SOURCE = "+source + " URL QUERY = "+query);
            //do something with the variables 
        }
    }
    

提交回复
热议问题