如何防止iframe中的链接在新标签页中打开

5
我为自己制作的基于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>

我认为这是不可能的 - Iulian Onofrei
3个回答

2
有两个选择:
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内容


-2
我在网上找到了这个答案:
window.open = function (url, name, features, replace) {
    document.getElementById('#iframe').src = url;
}

或者使用jQuery:

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

我还没有测试过,但是希望它能够正常工作。


3
如果你没有进行测试,请不要发布。 - Andrei

-4

添加 target="_self"

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

目标属性包括:

_self = 在点击的框架中打开链接文档(默认)

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

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

_top = 在窗口的完整主体中打开链接文档

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

信息来源:

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


8
您的意思是链接应该使用 <a href src="http://google.com" target="_self"></a>,而不是框架 <iframe src="http://google.com" target="_self"></iframe>,因为后者无法正常工作。 - SeekLoad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接