html
<div class="iframe-box">
<iframe id="iframes" src="" frameborder="0"></iframe>
</div>
style
.iframe-box {
width: 100%;
height:100%;
iframe {
display: block;
}
}
js
mounted () {
let _this = this;
let business_types = JSON.parse(localStorage.getItem("business_types"));
//vue+axios+iframe 引入公众号文章问题
let hrefUrl = business_types.pavilionUrl,
isWeiXin = isWeixinOrAlipay() === "weixin", //检测是否是微信浏览器
isqq = isWeixinOrAlipay() === "qq",
isPublicArticle = hrefUrl.indexOf("mp.weixin.qq.com") !== -1, //是否是公众号文章
iframe = $("#iframes");
//***iframe宽高进行处理 */
var dw = $(window).width(),
dh = $(window).height();
var cssText = "width:" + dw + "px !important;";
iframe.css("cssText",cssText);
if(navigator.userAgent.match(/(iPod|iPhone|iPad)/)){ //判断是苹果设备还是其他设备
iframe.attr("scrolling","no"); //评估设置设置为no
}else{
iframe.attr("scrolling","yes") //安卓设备设置为yes
iframe.height(dh)
}
/**
* 判断浏览器类型&&链接是否是公众号文章
* 1、返回的是公众号文章且是微信浏览器或QQ浏览器,则直接跳转该网址
* 2、如是公众号文章且不是微信浏览器或QQ浏览器,则通过ajax返回页面内容
* 3、如不是公众号且不是微信浏览器或QQ浏览器,则直接把网址放入iframe中
* */
if ((isWeiXin || isqq) && isPublicArticle) {
window.location.href = hrefUrl;
} else {
if (isPublicArticle) {
$.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
console.log("处理中:",options);
var http =
window.location.protocol === "http:" ? "http:" : "https:";
options.url = http + "//cors-anywhere.herokuapp.com/" + options.url;
}
});
$.get(hrefUrl, function(response) {
var html = response;
html = html
.replace(/data-src/g, "src")
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/g, "")
.replace(/https/g, "http");
var html_src = "data:text/html;charset=utf-8," + html;
// console.log("src有值-》:",html_src);
console.log("解析成功");
// _this.url = html_src;
// iframe.attr("src", html_src);
/**
* iframe srcdoc 解决安卓app某些页面会跳转到新的页面
* 此处注意是用srcdoc属性而不是用src
*/
iframe.attr("srcdoc",html );
});
} else {
iframe.attr("srcdoc",html );
// iframe.attr("src", hrefUrl);
}
}
}
isWeixinOrAlipay.js
/**
* 判断浏览器是微信还是支付宝
* @return {string} weixin->微信 alipay->支付宝 qq->QQ浏览器 false->其他
*/
export const isWeixinOrAlipay =function (){
var ua = window.navigator.userAgent.toLowerCase();
if(ua.indexOf('micromessenger') !== -1){
return "weixin";
}else if(ua.indexOf('alipay') !== -1){
return "alipay";
}else if(ua.match(/QQ/i)=='qq'){
return 'qq';
}else{
return false;
}
}