HTML阻止iframe跳转页面并使用iframe在页面内嵌微信网页版的实现方

2020-04-17 08:07:56易采站长站整理

就想弄一个winform结合html5的一个小东西,突有兴致,想在里面嵌套一个微信网页版。

好了,想法一出来,就行动吧,最终效果如下图:

一开始就打算在页面里面嵌套一个iframe指向https://wx.qq.com就OK了,但是我还是太天真,微信网页版会自动跳转。结果如下图:

于是上网搜了一下阻止iframe跳转的办法,就是在iframe标签加上security="restricted"sandbox="" 两个属性。前者是IE的禁止js的功能,后者是HTML5的功能。

使用

sandbox="allow-scripts allow-same-origin allow-popups"
可以阻止跳转。然而……结果却是这样:

然后发现,这个跳转其实就是关闭原先页面之后在浏览到跳转页面。所以可以利用页面关闭事件onbeforeunload来阻止跳转。所以在页面加入如下代码:


document.body.onbeforeunload = function (event) {
var rel = "asdfawfewf";
if (!window.event) {
event.returnValue = rel;
} else {
window.event.returnValue = rel;
}
};

然后发现结果还是这样:

到底是什么原因呢?事件没反应?还是微信网页版的跳转太牛了?直接无视这个事件?于是我新建一个空白的html,单独加上该事件进行验证。


<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body></body>
<script>
document.body.onbeforeunload = function (event) {
var rel = "asdfawfewf";
if (!window.event) {
event.returnValue = rel;
} else {
window.event.returnValue = rel;
}
};
</script>
</html>

结果却是可行的:

但是在页面里面嵌入iframe之后却直接就跳转了,大家可以尝试一下面的代码。


<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<iframe src="https://wx.qq.com/" frameborder="0" style="position: absolute;border: navajowhite;left: 0;height: calc(100% - 30px);width:100%">
</iframe>
</body>
<script>
document.body.onbeforeunload = function (event) {