Android WebView using GeolocationPermissions

那年仲夏 提交于 2019-12-03 21:34:47
Sherif elKhatib

It is rather simple when the html is your own. There are a couple of ways, I will give you 2 of them.

Simple way using GET

Idea is to send the location in the URL (you might need some encoding but as long as it's only numbers and no spaces you are fine

Some editing for your shouldOverridUrlLoading

public boolean shouldOverrideUrlLoading(WebView view, String url){
    if (url.needs_geo) //meaning if this is the url that needs the geo location
        url += "?geo=" + your_location;
    view.loadUrl(url);
    return true;
}

In your JavaScript:

function getParam(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

then

var geo_location = getParam('geo');

Using WebView.addJavascriptInterface

(I have never tried to pass values from Java to JavaScript but will probably work as well). The idea is to provide for your JavaScript a Java class that can be accessed to get the parameters you want to pass to JavaScript.

Inside your Activity class:

public String location; //as an example

    public class SherifJS {
        public String getLocation(){
            return location;
        }
    }
//bla bla

    SherifJS loc = new SherifJS();
    yourWebView.addJavascriptInterface(loc, "locationProvider"); 

Inside your JavaScript:

<script type="text/javascript">
        <!--

function sherifJS() {
    document.getElementById("locationHolder").innerHTML =
    window.locationProvider.getLocation();
}

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