[英]Remove target _blank for all hyper links in WebView
Err this is not related to android and this question is about to be marked as a duplicate of android related question. 错误,这与android无关,该问题将被标记为android相关问题的重复项。 ???
???
I need to remove target=_blank
from all hyper links so that all links will be opened in the same webview. 我需要从所有超级链接中删除
target=_blank
,以便所有链接都将在同一Web视图中打开。 When i searched for similar Q&As most of them suggested injecting a javascript which would convert all target=_blanks
to _self
. 当我搜索类似的Q&A时,他们中的大多数建议注入一个javascript,它将所有
target=_blanks
转换为_self
。 I am testing this in a browser window first, and the script indeed converts all hyperlinks but it has no effect, it still continues to open in a new window. 我首先在浏览器窗口中对此进行了测试,该脚本确实转换了所有超链接,但没有任何效果,它仍然继续在新窗口中打开。 How can I force it to open in same window/webview ?
如何强制在同一窗口/ WebView中打开它?
var a = document.getElementsByTagName("a");
for (i=0; i<a.length; i++)
if (a[i].target == "_blank")
a[i].target = "_self";
Actually, your JavaScript is correct. 实际上,您的JavaScript是正确的。 I suspect you've created test html page to check it.
我怀疑您已经创建了测试html页面进行检查。 In this case, you need to place script in the end of page, otherwise it will not affect links:
在这种情况下,您需要将脚本放在页面末尾,否则不会影响链接:
<body>
<!-- This will work -->
<a target="_blank" href="https://google.com">google.com</a>
<script>
var a = document.getElementsByTagName("a");
for (i=0; i<a.length; i++)
if (a[i].target == "_blank")
a[i].target = "_self";
</script>
<!-- This link will not be modified -->
<a target="_blank" href="https://google.com">google.com</a>
</body>
You need to inject this script in your WebView
. 您需要将此脚本注入
WebView
。 Use following code in your WebFrameLoadDelegate
: 在您的
WebFrameLoadDelegate
使用以下代码:
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
NSString *script = @"var a = document.getElementsByTagName(\"a\");\n" \
"for (i=0; i<a.length; i++) {\n" \
" if (a[i].target == \"_blank\") {\n" \
" a[i].target = \"_self\";\n" \
" }\n" \
"};";
[frame.javaScriptContext evaluateScript:script];
}
Note that this script should be performed for each frame separately. 请注意,应针对每个帧分别执行此脚本。
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.