H5页面兼容微信内置功能wx.ready,wx.getLocation在iframe内遇到无法获取位置也不报错问题

本文介绍了解决在HTML5项目中使用iframe嵌套页面导致wx.js接口如wx.getLocation()失效的方法。通过将wx.config和wx.ready放置在外层页面而非内嵌页面中,成功实现了接口功能。

前提:本人项目中HTML5使用了iframe嵌套页面,在嵌套页面使用wx.getLocation()一直没有效果。
然后发现wx.config和wx.ready不能放在内嵌页面,否则访问不到,正确代码如下。
外层页面代码:(部分)

 <div class="bottom-nav">
			<ul>
				<li class="j-bottomalink active">
					<a href="<%=basePath%>weChat/index/volunteerView" target="tabmain">
						<label><i class="icon iconfont icon-index-0-copy"></i></label>
						<font>首页</font>
					</a>
				</li>
</div>

<script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=vFF2LptWMc4jGe7e8H4O3nnHuHgY6Lzc"></script>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>	
	$(function(){
            	config();
    })

 //权限配置
            function config(){
				$.ajax({
				    url : "/weChat/index/wxConfig",
				    type : "post",
				    data : {
				    	url:location.href.split('#')[0],
				        debug: false,
				        jsApiList: ['getLocation', 'openLocation']
				    },
				    datatype : "json",
				    success : function(data, textStatus) {
				    	console.log(eval('(' + data + ')'));
				        wx.config(eval('(' + data + ')'));
				        wx.error(function (res) {
			            alert("微信权限获取失败");
			        	}); 
				    }
				}) 
			}
          
          //微信获取定位
            wx.ready(function () {
				wx.getLocation({
					  type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
					  success: function (res) {
						  var storage=window.localStorage;//本地缓存
				          storage["lat"] = res.latitude; // 纬度,浮点数,范围为90 ~ -90
				          storage["lng"] = res.longitude; // 经度,浮点数,范围为180 ~ -180。
						  $(".bottom-nav ul li a").get(0).click();
					  }
				});
				 wx.error(function (res) {
		            alert("地理位置获取失败");
		        }); 
            })

内嵌页面代码:(部分)

$(document).ready(function() {
				 //权限配置
	            //config();
	            });

function getDIstance(){
	            storage=window.localStorage;//本地缓存
      	         lat1 = storage["lat"]; // 纬度,浮点数,范围为90 ~ -90
      	            lng1 = storage["lng"]; // 经度,浮点数,范围为180 ~ -180。
      	            distance = GetDistance(lat1,lng1,lat2,lng2).toFixed(1);
			    if(distance>1000){
      	            	distance=(distance/1000).toFixed(1)+'k'
      	            }
			    if(distance!="NaN"){
			    	$("#distance_"+item.id).html(distance+" 公里");
      	            }
      	            //微信获取定位
      	            /* wx.ready(function () {
      					wx.getLocation({
      						  type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
      						  success: function (res) {
      						    lat1 = res.latitude; // 纬度,浮点数,范围为90 ~ -90
      						    lng1 = res.longitude; // 经度,浮点数,范围为180 ~ -180。
      						    distance = GetDistance(lat1,lng1,lat2,lng2).toFixed(1);
      						    if(distance>1000){
	        	            	distance=(distance/1000).toFixed(1)+'k'
	        	            }
      						    if(distance!="NaN"){
      						    	$("#distance_"+item.id).html(distance+" 公里");
	        	            }
      						  }
      					});
      				}) */
      			
       	    	html+='<li class="project" dataId="'+item.id+'">';
       	    	html+='<div class="imgbox"><img src="<%=basePath%>'+item.projectImage+'" /></div>'
       	    	html+='<div class="text">'
       	    	html+='<p>'+longProjectName(item.projectName)+'</p>'
       	    	html+='<font>'+(item.vtTeam==null?"":longProjectName(item.vtTeam.teamName))+'</font>'
       	    	html+='<font>发起:'+(item.createTime.substring(0,10))+'<span style="margin-left:40px;width:120px;"><img src="<%=basePath%>/resources/wechat/images/icon11.png" style="width:.3rem;margin-right:5px;"><font id="distance_'+item.id+'">'+distance+' 公里</font></span></font>'
       	    	html+='</div>'
       	    	html+='</li>'
       	    	}

//权限配置
            /* function config(){
				$.ajax({
				    url : "/weChat/index/wxConfig",
				    type : "post",
				    data : {
				    	url:location.href.split('#')[0],
				        debug: true,
				        jsApiList: ['getLocation', 'openLocation']
				    },
				    datatype : "json",
				    success : function(data, textStatus) {
				    	console.log(eval('(' + data + ')'));
				        wx.config(eval('(' + data + ')'));
				        wx.error(function (res) {
				            alert("config错误");
				        }); 
				    }
				})
			}  */

注意点:
之所以发现在iframe页面访问不到wx.config,是开启了wx.config的debug为true,但是内嵌页面没有任何alert。把wx.config放到外层页面就能看到alert说明内部无法使用wx.config和wx.ready。

### 使用 `wx.getLocation` API 在企业微信 H5 页面获取用户地理位置 在企业微信 H5 页面中使用 `wx.getLocation` 接口来获取用户的地理位置信息,可以通过以下方式实现: #### 配置 JSSDK 权限签名 为了调用微信 JS-SDK 的接口,在页面加载时需要先通过服务端配置权限验证签名。这一步骤确保了前端能够安全地调用相关接口。 ```javascript // 假设已经完成了 wx.config 的初始化工作 wx.config({ debug: false, appId: 'your-app-id', timestamp: timestamp, nonceStr: noncestr, signature: signature, jsApiList: ['getLocation'] }); ``` #### 调用 getLocation 方法 完成上述配置之后,便可以在适当的地方调用 `wx.getLocation` 方法以获得地理坐标数据[^2]。 ```javascript wx.getLocation({ type: 'wgs84', // 默认为 wgs84 返回 gps 经纬度,可选 gcj02 返回可用于 wx.openLocation 的经纬度 success(res) { const latitude = res.latitude; const longitude = res.longitude; console.log(`Latitude:${latitude}, Longitude:${longitude}`); // 可在此处继续处理位置信息,例如显示地图或计算距离等操作 // 如果还需要进一步展示位置,则可以配合 openLocation 使用 /* wx.openLocation({ latitude, longitude, scale: 18, name: '某地点名称', address: '具体地址描述' }); */ }, fail(err){ console.error('Failed to get location:', err); } }); ``` 需要注意的是,当在一个 iframe 中尝试调用这些方法时可能会遇到一些特殊的情况,如无法正常触发回调等问题。此时建议将 `wx.config` 放置于最外层页面执行,并确认所有必要的参数都已正确传递给子页面[^4]。 另外,考虑到用户体验以及隐私保护的要求,在实际开发过程中应当遵循合理的提示机制告知用户为何请求其分享当前位置,并提供清晰的操作指引;同时也要做好异常情况下的友好反馈设计,保障即使未能成功取得位置也能让用户顺利完成其他交互流程[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值