window.name跨域通讯小坑一记

本文探讨了在支付完成后延迟跳转至商户广告页面的需求,分析了window.name、sessionStorage和localStorage作为标记存储介质的优劣。在不同设备环境下,如PC、安卓、iOS等,对这些方法进行了测试,并提出了针对iOS11以上版本和华为P20的解决方案。

工作中有这么一个需求,在支付完成之后,延迟3秒跳转到商户的广告页面。在广告页面通过返回按钮,可以再次返回到支付完成的详情页面,但此时延迟3秒后不会再次跳转到商户广告页面。

很明显,需要存一个标记,表示是否已经跳转过了。当时觉得window.name应该就可以胜任这个任务。

window.name

我们在js里面随时可以获取window对象,window对象有一个name属性,如下所示:
在这里插入图片描述
这个name属性代表了这个窗口的名称,可以读取和设置,大小不超过2MB。最重要的是,name在这个窗口(注意是窗口,不是浏览器)关闭之前,内容会一直保存着。跨域的两个地址,都可以读取到这个name值,那么跨域问题就很巧妙的被绕过去了。另外网站不论如何跳转,只要没有被修改过,返回后都可以继续读取到这个值。

然后回到我们的问题,我可以将跳转标记存到name属性里面,那么从商户广告返回来之后,如果跳转标记已经有值了,说明已经跳转过了,那么就不允许再跳了。测试代码如下:

 /*要跳转的网址*/
    var hrefUrl="https://www.baidu.com";
    /*间隔的时间*/
    var time = 3000;
    
    /*跳转方法*/
    function jump(hrefUrl,time) {
        if (window.name === "jumped") {
            console.log("已经跳转过了,不需要进行再次跳转")
        } else {
            window.name = "jumped";
            setTimeout(function () {
                window.location.href = hrefUrl;
            }, time);
        }
    }

    window.onload = function () {
        jump(hrefUrl,time);
    };

代码在pc上、安卓手机、低版本ios(10及以下)上都运行很好,在ios11却不停的跳转。经过断点debug,发现window.name被清空了,看来高版本的safari干了坏事。
因此window.name是一个比较鸡肋的功能了,如果要跨域,可以使用jsonp的方式。如果仅仅是存一个标记,可以使用sessionStorage或者localStorage。这里我采用了sessionStorage存储跳转标记。

 /*要跳转的网址*/
    var hrefUrl="https://www.baidu.com";
    /*间隔的时间*/
    var time = 3000;

    /*跳转方法*/
    function jump(hrefUrl,time) {
        if (window.sessionStorage.getItem('jumped') === "jumped") {
            console.log("已经跳转过了,不需要进行再次跳转")
        } else {
            window.sessionStorage.setItem('jumped','jumped');
            setTimeout(function () {
                window.location.href = hrefUrl;
            }, time);
        }
    }

    window.onload = function () {
        jump(hrefUrl,time);
    };

localStorage存储是永久的,没有过期时间,必须要自己remove掉内容,比较麻烦。sessionStorage的存储有效期是窗口打开期间,清除时机是在会话结束。会话结束是在用户关闭标签页或者关闭窗口的时候。即使网址变过,只要重新输入,sessionStorage都可以恢复。但是手动新开一个标签或窗口时,会新开会话,即使链接一样,也不会共享sessionStorage。sessionStorage在同一个域下,是共享的。

从商户广告跳转回来后,重新输入了地址,sessionStorage恢复了,因此可以继续获取到跳转标记,同样可以判断是否已经跳转过了,问题也得到了解决。但是要明白一点,商户页面肯定是获取不到sessionStorage的内容的,因为不在同一个域。

2019.9.23 记
使用sessionStorage的时候,发现华为p20第一次跳转后返回,标记并没有保存下来,导致再跳转了一次。第二次跳转返回后,读取到了标记,才没有再跳转了。最后使用了sessionStorage+window.name组合的方式。
如果可以的话,使用localStorage可能会更方便点,我这里没有办法清除掉localStorage内容,所以没有采用。

<!-- hybrid/html/map.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>高德地图</title> <!-- <script src="https://webapi.amap.com/loader.js"></script> --> <script src="https://cdn.bootcss.com/vue/2.6.11/vue.js"></script> <style> #map-container { width: 100%; height: 584px; border-radius: 22px; z-index: 4; } /* 新增:隐藏高德默认标记图标 */ #map-container .amap-marker img[src*="mark_bs.png"] { display: none !important; } </style> </head> <body> <div id="map-container"></div> <script type="text/javascript" src="./js/uni.webview.0.1.52.js"> </script> <script> window._AMapSecurityConfig = { securityJsCode: 'cf331d54f67e306ca5c0b17f7122d559' }; </script> <script src="https://webapi.amap.com/maps?v=2.0&key=f3323c24769b10828db07f07c0fcec0d&plugin=AMap.MarkerCluster"> </script> <script src="https://webapi.amap.com/ui/1.1/main.js"></script> <script> // 确保UniApp通信桥接准备就绪 function setupUniBridge() { return new Promise(resolve => { if (typeof uni.postMessage === 'function') { return resolve(); } document.addEventListener('UniAppJSBridgeReady', resolve); }); } // 向UniApp发送消息(兼容H5和App环境) async function sendMessageToUniApp(data) { // 1. 确保桥接就绪(仅对App环境有效,H5环境会直接resolve) await setupUniBridge(); // 2. 区分环境发送消息 if (isH5Environment()) { // H5环境:使用浏览器原生postMessage console.log('H5环境,使用window.parent.postMessage发送消息'); window.parent.postMessage({ type: 'webviewMessage', // 自定义类型,方便UniApp识别 data: JSON.stringify(data) }, '*'); // 第三个参数为目标名,*表示允许所有(开发环境可用,生产环境需指定具体名) } else if (window.uni && typeof uni.postMessage === 'function') { // App环境:使用uni.postMessage console.log('App环境,使用uni.postMessage发送消息'); uni.postMessage({ data: JSON.stringify(data) }); } else { console.error('未支持的环境,无法发送消息'); } } // 辅助函数:判断是否为H5环境(浏览器环境) function isH5Environment() { const protocol = window.location.protocol; // H5环境的协议通常是http:或https: return protocol === 'http:' || protocol === 'https:'; } // 解析URL参数 const params = new URLSearchParams(location.search); const points = JSON.parse(params.get('points') || '[]'); const markers = JSON.parse(params.get('markers') || '[]'); // 初始化地图 const map = new AMap.Map('map-container', { zoom: 10, center: [points[0].lng, points[0].lat], showBuildingBlock: true }); // 自定义单个标记内容(保持原有样式,修复图片路径) function createMarkerContent(markerData) { // 优先使用本地图片,失败则用备用图(确保是自定义图标) const imageUrl = './img/flag.png'; return ` <div style="position:relative;z-index:1000;"> <img src="${imageUrl}" style="width:30px; height:30px;" alt="${markerData.title}"> <div style="position:absolute; bottom:-20px; left:50%; transform: translateX(-50%); background: #f5e7e7; padding:3px 8px; border-radius: 18px; white-space:nowrap; font-family:ShuHuiTi, sans-serif; font-size: 12px; font-weight: bold; border: 2px solid #F47C58; color:#E4393C;"> ${markerData.title} </div> </div> `; } // 聚合点渲染函数 function _renderClusterMarker(context) { const count = context.count; console.log('渲染聚合点,数量:', count); // 通过JS直接设置样式(优先级更高) const div = document.createElement('div'); div.innerHTML = count; // 强制设置关键样式(覆盖默认) div.style.width = '40px'; div.style.height = '40px'; div.style.backgroundColor = '#FF9A44'; div.style.borderRadius = '50%'; div.style.display = 'flex'; div.style.alignItems = 'center'; div.style.justifyContent = 'center'; div.style.color = 'white'; div.style.fontWeight = 'bold'; // 设置聚合点偏移(确保居中) context.marker.setOffset(new AMap.Pixel(-20, -20)); context.marker.setContent(div); // 通过context.marker设置内容 } // 单个标记渲染函数 function _renderMarker(context) { const markerData = context.data[0].originalData; // 1. 生成标记内容 const content = createMarkerContent(markerData); // 2. 设置标记内容 context.marker.setContent(content); // 3. 校准偏移量(根据内容尺寸计算,确保标记中心与经纬度对齐) // 内容总高度:图片30px + 标题区20px = 50px,向上偏移50px使底部对齐定位点 context.marker.setOffset(new AMap.Pixel(-15, -50)); // 水平偏移:30px宽/2=15px // 4. 绑定点击事件 context.marker.on('click', async () => { const message = { type: 'markerClick', data: markerData }; console.log('H5发送消息:', message); // 优先使用uni.postMessag await sendMessageToUniApp({ type: 'markerClick', data: markerData }); }); } // 绘制路线(保持原有功能) function drawRouteAndPoints() { if (points.length === 0) return; const path = points.map(p => [p.lng, p.lat]); new AMap.Polyline({ path: path, strokeColor: "#32CD32", strokeWeight: 5, zIndex: 500, map: map }); if (points.length >= 2) { AMap.plugin('AMap.Driving', () => { const driving = new AMap.Driving({ map: map, policy: AMap.DrivingPolicy.LEAST_TIME, zIndex: 550 }); driving.search( [points[0].lng, points[0].lat], [points[points.length - 1].lng, points[points.length - 1].lat] ); }); } } // 初始化聚合标记 function initClusterMarkers() { if (!markers.length) return; // 转换数据格式为官方示例要求的结构(包含lnglat字段) const clusterPoints = markers.map(marker => ({ lnglat: new AMap.LngLat(marker.lng, marker.lat), // 官方要求的经纬度格式 originalData: marker // 保留原始数据供渲染使用 })); // 参考官方示例:插件加载后初始化聚合 AMap.plugin('AMap.MarkerCluster', function() { if (typeof AMap.MarkerCluster === 'undefined') { console.error('聚合插件加载失败'); return; } // 配置聚合参数 const cluster = new AMap.MarkerCluster(map, clusterPoints, { gridSize: 80, // 网格大小(官方示例默认60,可调整) maxZoom: 15, // 最大聚合级别 minClusterSize: 2, // 最小聚合数量(测试时可改为1) zoomOnClick: true, averageCenter: true, zIndex: 2000, // 聚合点参数名 renderClusterMarker: _renderClusterMarker, // 单个标记参数名 renderMarker: _renderMarker }); // 调整视野 const bounds = new AMap.Bounds(); clusterPoints.forEach(point => bounds.extend(point.lnglat)); map.setBounds(bounds, [50, 50, 50, 50]); }); } // 地图加载完成后初始化 map.on('complete', function() { console.log('地图加载完成,初始化组件'); initClusterMarkers(); if (points.length > 0) drawRouteAndPoints(); }); map.on('error', (err) => console.error('地图错误:', err)); // 构建带标题的HTML内容 // markers.forEach(marker => { // // 构建HTML内容(包含图片和标题) // const content = ` // <div style="background: linear-gradient(180deg, #E3383B 0%, #F47C58 98%); padding:6px; border-radius: 8px;"> // <div style=" white-space:wrap; // font-family:AlibabaPuHuiTi-SemiBold; font-size: 15px; // margin-top:5px;color:#fff;width:100%;">闽宁新貌展示中心</div> // <div style=" white-space:wrap;text-indent: 1em;letter-spacing: 1px; // font-family:AlibabaPuHuiTi-RegularL3; font-size: 10px; // margin-top:5px;color:#fff;width:100%;"> // 闽宁新貌展示中心,生动呈现闽宁协作丰硕成果,见证昔日“干沙滩”蜕变为今日“金沙滩”的壮丽历程。 </div> // <img src="./img/ditu.png" style="width:200px; height:110px; display:block;margin-top:5px;"> // </div> // `; // const markerObj = new AMap.Marker({ // position: [marker.lng, marker.lat], // content: content, // 使用HTML内容 // anchor: 'bottom-center', // 锚点在底部中心 // offset: new AMap.Pixel(0, -25) // 向上偏移 // }); // markerObj.on('click', () => { // console.log('window--uni', uni, window); // // console.log(marker, '000'); // // 将数据转为字符串 // const message = JSON.stringify({ // type: 'markerClick', // title: marker.title // }); // window.parent.postMessage(message, '*'); // // 通过uni.postMessage发送数据 // // uni.postMessage({ // // data: JSON.stringify(message) // 发送字符串 // // }); // }); // map.add(markerObj); // }); // 2. 在map加载完成后初始化聚合点 // map.on('complete', function() { // // 创建聚合实例 // const cluster = new AMap.MarkerClusterer(map, markers.map(m => { // return new AMap.Marker({ // position: [m.lng, m.lat], // content: createMarkerContent(m) // 自定义标记 // }); // }), { // gridSize: 80, // maxZoom: 18, // renderClusterMarker: renderCluster // }); // // // 转换数据格式 // // const clusterPoints = markers.map(marker => ({ // // lnglat: [marker.lng, marker.lat], // // title: marker.title, // // originalData: marker // 保留原始数据 // // })); // // console.log('在map加载完成后初始化聚合点', clusterPoints); // // // 确保有聚合点数据 // // if (clusterPoints.length === 0) return; // // 使用MarkerCluster插件 // // AMap.plugin('AMap.MarkerCluster', function() { // // console.log("聚合插件加载完成"); // // // 创建聚合点 // // const cluster = new AMap.MarkerCluster(map, clusterPoints, { // // gridSize: 80, // 聚合网格像素大小 // // maxZoom: 18, // 最大聚合级别 // // minClusterSize: 2, // 最小聚合数量 // // zoomOnClick: true, // 点击聚合点是否放大地图 // // averageCenter: true, // 聚合点是否使用平均值中心 // // // 定义聚合点样式 // // renderClusterMarker: function(context) { // // console.log('定义聚合点样式-context', context); // // // const count = context.count; // // // const div = document.createElement('div'); // // // div.innerHTML = ` // // // <div style="background: #FF9A44; // // // border-radius: 50%; // // // width: 40px; // // // height: 40px; // // // display: flex; // // // align-items: center; // // // justify-content: center; // // // color: white; // // // font-weight: bold; // // // z-index:99;"> // // // ${count} // // // </div> // // // `; // // const count = context.count; // // const div = document.createElement('div'); // // div.style.background = '#FF9A44'; // // div.style.borderRadius = '50%'; // // div.style.width = '40px'; // // div.style.height = '40px'; // // div.style.display = 'flex'; // // div.style.alignItems = 'center'; // // div.style.justifyContent = 'center'; // // div.style.color = 'white'; // // div.style.fontWeight = 'bold'; // // div.style.zIndex = '99'; // // div.innerHTML = count; // // // context.marker.setContent(div); // // return div; // // }, // // // 自定义标记点样式 // // renderMarker: function(context) { // // const markerData = context.data[0].originalData; // // // console.log('自定义标记点样式-context', context); // // // const marker = new AMap.Marker({ // // // position: [markerData.lng, markerData.lat], // // // content: ` // // // <div style="position:relative; text-align:center;z-index:100;"> // // // <img src="./img/flag.png" // // // style="width:40px; height:50px; display:block;"> // // // <div style="position:absolute; bottom:-90%; left:0%; transform:translateX(-50%); // // // background: rgba(227, 57, 59, 0.1); padding:6px 0; // // // border-radius: 18px; white-space:wrap; // // // font-family:ShuHuiTi; font-size: 12px;font-weight: bold; // // // margin-top:5px;border: 2px solid #F47C58;color:#E4393C;width:80px;"> // // // ${markerData.title} // // // </div> // // // </div> // // // `, // // // offset: new AMap.Pixel(0, 0) // // // }); // // // 创建自定义内容 // // const content = ` // // <div style="position:relative; text-align:center;z-index:100;"> // // <img src="./img/flag.png" style="width:40px; height:50px; display:block;"> // // <div style="position:absolute; bottom:-90%; left:50%; transform:translateX(-50%); // // background: rgba(227, 57, 59, 0.1); padding:6px 0; font-family:ShuHuiTi; font-size: 12px;font-weight: bold; // // margin-top:5px;border: 2px solid #F47C58;color:#E4393C;width:80px; border-radius: 18px;"> // // ${markerData.title} </div> </div> `; // // const marker = new AMap.Marker({ // // position: [markerData.lng, markerData.lat], // // content: content, // // offset: new AMap.Pixel(-2, -4) // 根据实际图片调整偏移 // // }); // // // 绑定聚合点点击事件 // // // marker.on('click', async function(e) { // // // console.log(e, 'bbbbb'); // // // sendMessageToUniApp({ // // // type: 'markerClick', // // // center: e.lnglat // // // }); // // // }); // // // // console.log('聚合点点', marker); // // // map.add(marker); // // // 绑定标记点击事件 // // marker.on('click', async function(e) { // // 发送消息给UniApp // // await sendMessageToUniApp({ // // type: 'markerClick', // // data: markerData // // }); // // }); // // return marker; // // }, // // }); // // // 绑定聚合点点击事件 // // cluster.on('click', async function(e) { // // console.log(e, 'bbbbb'); // // // 发送聚合点点击事件 // // await sendMessageToUniApp({ // // type: 'clusterClick', // // data: { // // count: e.clusterData.count, // // center: e.clusterData.center, // // markers: e.clusterData.markers // // } // // }); // // }); // // }); // }); // 2. 绘制路线 // const path = points.map(p => [p.lng, p.lat]); // new AMap.Polyline({ // path: path, // strokeColor: "#32CD32", // strokeWeight: 5, // map: map // }); // 3. 添加起点终点标记 // points.forEach((point, i) => { // new AMap.Marker({ // position: [point.lng, point.lat], // // content: `<div class="point-label">${i === 0 ? '起' : '终'}</div>`, // offset: new AMap.Pixel(-10, -10), // map: map // }); // }); // 4. 绘制驾车路径(如果需要,可以注释掉直线路径,保留驾车路径) // 注意:这里同时绘制了直线和驾车路径,可能会重叠 // if (points.length >= 2) { // AMap.plugin('AMap.Driving', () => { // const driving = new AMap.Driving({ // map: map, // 这样驾车路线会直接显示在地图上 // policy: AMap.DrivingPolicy.LEAST_TIME // }); // driving.search( // [points[0].lng, points[0].lat], // [points[points.length - 1].lng, points[points.length - 1].lat], // (status, result) => { // // 可以根据结果处理 // } // ); // }); // } // 1. 绘制路线 // if (points.length > 0) { // const path = points.map(p => [p.lng, p.lat]); // new AMap.Polyline({ // path: path, // strokeColor: "#32CD32", // strokeWeight: 5, // map: map // }); // // 添加起点终点标记 // points.forEach((point, i) => { // new AMap.Marker({ // position: [point.lng, point.lat], // offset: new AMap.Pixel(-10, -10), // map: map // }); // }); // // 绘制驾车路径(如果需要) // if (points.length >= 2) { // AMap.plugin('AMap.Driving', () => { // const driving = new AMap.Driving({ // map: map, // policy: AMap.DrivingPolicy.LEAST_TIME // }); // driving.search( // [points[0].lng, points[0].lat], // [points[points.length - 1].lng, points[points.length - 1].lat] // ); // }); // } // } </script> </body> </html>点击点标记只有console.log('H5发送消息:', message);这个打印,其他的没有反应
最新发布
08-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值