Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GeoLocation in a webview inside a Chrome Packaged App

I'm trying to get geolocation inside a webview in a Chrome Packaged App, in order to run my application properly. I've tried several ways to get the permission in manifest.json and injecting scripts, but it doesn't work and doesn't show any error message.

Could someone give me a light or a solution to get permission and show my geolocation?

like image 638
brunowindrop Avatar asked Jan 17 '26 05:01

brunowindrop


1 Answers

Some features that usually require permissions in a normal web page are also available in a webview. However, instead of the normal popup "the website xyz.com wants to know your physical location - allow / deny", the app that contains the webview needs to explicitly authorize it. Here is how it works:

  • No need to change the web page inside the webview;

  • In the app, you listen for permissionrequest events on the <webview> element:

webview.addEventListener('permissionrequest', function(e) {
  if ( e.permission === 'geolocation' ) {
    e.request.allow();
  } else {
    console.log('Denied permission '+e.permission+' requested by webview');
    e.request.deny();
  }
});

One thing to note is that the request doesn't need to be handled immediately. You can do whatever you need to do before allowing or denying, as long as you call preventDefault in the permissionrequest event and keep the event object from being garbage collected. This is useful if you need to do any async operation, like going to a storage to check if the URL requesting a permission should be allowed or not.

For example:

webview.addEventListener('permissionrequest', function(e) {
  if ( e.permission === 'geolocation' ) {
    // Calling e.preventDefault() is necessary to delay the response.
    // If the default is not prevented then the default action is to
    // deny the permission request.
    e.preventDefault();
    setTimeout(function() { decidePermission(e); }, 0);
  }
});

var decidePermission = function(e) {
  if (e.url == 'http://www.google.com') {
    e.request.allow();
  }
  // Calling e.request.deny() explicitly is not absolutely necessary because
  // the request object is managed by the Javascript garbage collector.
  // Once collected, the request will automatically be denied.
  // If you wish to deny immediately call e.request.deny();
}
  • Also note that your app needs to also request the respective permission:
"permissions": ["geolocation"],

The webview sample has more code for other permissions, like pointerLock and media capture.

like image 156
mangini Avatar answered Jan 19 '26 18:01

mangini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!