微信客戶端跨域分享iframe內的內容
1、首先要保證有這兩個網站的修改許可權
2、應用場景:A站可以通過微信直接分享,B站沒有申請相關許可權,B站作為iframe源,我們通過A站去分享B站的內容
3、在A站iframe所在頁面加入以下指令碼,並且引用jquery.base64
var title=null;$.base64.utf8encode = true;if(getQueryString("data")){document.title=JSON.parse($.base64.atob((getQueryString("data")), true)).title;}function isWeiXin() {var ua = window window.onload=function(){//postmessage(引數,子頁面域名)document.querySelector("#myiframe").contentWindow.postMessage('getData','http://rainbow6s.org');};window.addEventListener('message',function(e){var data=JSON.parse(e.data);if(!isWeiXin()){ return ; }if($("#myiframe").attr("src" $(function () {if(getQueryString("data")){$("#myiframe").attr("src",JSON.parse($.base64.atob((getQueryString("data")), true)).url);}else {$("#myiframe").attr("src",url);} }); |
其中“myiframe”為iframe的ID。
B站所有頁面加入以下指令碼
window.addEventListener('message',function(e){if(e.source!=window.parent) return;window.parent.postMessage(JSON.stringify({"url":window.location.href,"title":document.title}),'*');},false);$(function () {window.parent.postMessage(JSON.stringify({"url":window.location.href,"title":document.title}),'*');}); |
4、思路解釋:
建立A與B的通訊後,只要B跳轉到其他頁面(或者說:只要B站當前HTML文件載入完畢),就會通過JSON給A傳送它目前的地址以及文件標題,A站在接收到資訊後,會判斷iframe的src和傳來的url是否相同,如果相同則說明不需要進行處理,不相同,則將傳來的src作為引數傳遞給當前頁面(這些引數需要使用base64進行處理否則會亂碼),並重新載入當前頁面。當前頁面在載入後會判斷當前頁面的url裡是否有引數,如果有引數則解密引數,並將引數中的url賦給iframe的src,其中的title賦值給當前頁面。需要注意的是最後的操作要在微信JSSDK執行前執行。 |