如何防止iframe中的链接在新选项卡中打开

How to prevent links in iframe from opening in new tab

本文关键字:选项 新选项 iframe 何防止 链接      更新时间:2023-09-26

我为自己制作的基于web的操作系统制作了一个基于web的小浏览器。我注意到,在一些网站上,他们有喜欢在新标签页中打开的链接。有没有一种方法可以防止这种情况,并在iframe中打开链接?

这是我为整个浏览器编写的代码,以防万一:

<html>
<head>
<link href="./browser.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript"  src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$(function() {
$("#load").click(function() {
var new_url = $("#url").val();
// Checks that the user typed "http://" or not
if(new_url.substr(0,7)!="http://")
new_url = "http://"+new_url;
$("#main_frame").attr("src", new_url);
});
});
</script>
</head>
<body>
<div id="help">
<form action="help.html"><input type="submit" value="Help"></form>
</div>
Address:
<div id="logo">
<img src="stallion.png">
</div>
<input type="text" style="width: 400px;" name="url" id="url">
<input type="button" value="Go" id="load">
<div>
<input type="image" src="back.png" height=25 width=25 onclick="back()">
<input type="image" src="forward.png" height=25 width=25 onclick="forward()">
<input type="image" src="refresh.png" height=26 width=26 onclick="refresh()">
</div>
<iframe frameborder=0 class="netframe" src="http://www.bing.com/" id="main_frame"></iframe>
</body>
<script>
function back()
{
window.history.back();
}
</script>
<script>
function forward()
{
window.history.forward();
}
</script>
<script>
function refresh()
{
var iframe = document.getElementById('main_frame');
iframe.src = iframe.src;
}
</script>
</html>

有两种选择

1:您可以在每次更改时检查iframe中的所有html,并查找"target=_blank",如果是,则替换为"target=_self"

2:我认为更好的方法是,当用户单击锚标记检查锚是否具有属性"target=_blank"时,只需删除它,然后单击链接。

我在下面提供了一个jsFiddle

https://jsfiddle.net/L5dhp80e/

Html

<a class="newTab" href="http://www.google.com" target="_blank">
    New Tab Google
</a>
<br />
<a class="removeBlank" href="http://www.google.com" target="_blank">
    Removed Target Blank Google
</a>

Javascript

$(function () {
    $('a.removeBlank').on('click', function () {
        if ($(this).attr('target') == "_blank") {
            $(this).attr('target', '_self');
        }
        $(this).click();
        return false;
    })
});

但是,如果iframe内容是跨域的,我认为您根本无法编辑任何代码。

获取跨域iframe 的DOM内容

我在网上找到了这个答案:

window.open = function (url, name, features, replace) {
    document.getElementById('#iframe').src = url;
}

或者使用jQuery:

window.open = function (url, name, features, replace) {
    $('#iframe').attr('src', url);
}

我还没有测试过,但我希望它能起作用。

添加target="_self"

<iframe src="http://google.com" target="_self"></iframe>

目标属性为:

_self=在单击的同一框架中打开链接文档(这是默认设置)

_blank=在新窗口或选项卡中打开链接的文档

_parent=在父框架中打开链接的文档

_top=在窗口的全文中打开链接的文档

framename=在命名框架中打开链接文档

信息来源:

http://www.w3schools.com/tags/att_a_target.asp