codecamp

管理位置权限

Web组件提供位置权限管理能力。开发者可以通过onGeolocationShow()接口对某个网站进行位置权限管理。Web组件根据接口响应结果,决定是否赋予前端页面权限。获取设备位置,需要开发者配置ohos.permission.LOCATION权限。

在下面的示例中,用户点击前端页面"获取位置"按钮,Web组件通过弹窗的形式通知应用侧位置权限请求消息,示例代码如下:

  • 前端页面代码。
    1. <!DOCTYPE html>
    2. <html>
    3. <body>
    4. <p id="locationInfo">位置信息</p>
    5. <button onclick="getLocation()">获取位置</button>
    6. <script>
    7. var locationInfo=document.getElementById("locationInfo");
    8. function getLocation(){
    9. if (navigator.geolocation) {
    10. <!-- 前端页面访问设备地理位置 -->
    11. navigator.geolocation.getCurrentPosition(showPosition);
    12. }
    13. }
    14. function showPosition(position){
    15. locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude;
    16. }
    17. </script>
    18. </body>
    19. </html>
  • 应用代码。
    1. // xxx.ets
    2. import web_webview from '@ohos.web.webview';
    3. @Entry
    4. @Component
    5. struct WebComponent {
    6. controller: web_webview.WebviewController = new web_webview.WebviewController();
    7. build() {
    8. Column() {
    9. Web({ src:$rawfile('getLocation.html'), controller:this.controller })
    10. .geolocationAccess(true)
    11. .onGeolocationShow((event) => { // 地理位置权限申请通知
    12. AlertDialog.show({
    13. title: '位置权限请求',
    14. message: '是否允许获取位置信息',
    15. primaryButton: {
    16. value: 'cancel',
    17. action: () => {
    18. event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求
    19. }
    20. },
    21. secondaryButton: {
    22. value: 'ok',
    23. action: () => {
    24. event.geolocation.invoke(event.origin, true, false); // 允许此站点地理位置权限请求
    25. }
    26. },
    27. cancel: () => {
    28. event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求
    29. }
    30. })
    31. })
    32. }
    33. }
    34. }
在新窗口中打开页面
应用侧调用前端页面函数
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录
HAR

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }