2

Err this is not related to android and this question is about to be marked as a duplicate of android related question. ???

I need to remove target=_blank from all hyper links so that all links will be opened in the same webview. When i searched for similar Q&As most of them suggested injecting a javascript which would convert all target=_blanks to _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 ?

var a = document.getElementsByTagName("a");
for (i=0; i<a.length; i++)
    if (a[i].target == "_blank")
        a[i].target = "_self";
user88975
  • 1,618
  • 3
  • 19
  • 29
  • Have you checked if the loop ever runs? Maybe there are no `a` tags at the time you're executing your script. – Teemu Jan 03 '14 at 12:58
  • Make sure that you place this script after all the DOM elements are loaded. – Ishank Gupta Jan 03 '14 at 12:59
  • @Teemu I Am testing this script in a Browser(Chrome), and am injecting this through console. And I can verify that target has been changed through developer inspector tools. – user88975 Jan 03 '14 at 13:06
  • possible duplicate of [Link should be open in same web view in Android](http://stackoverflow.com/questions/7308904/link-should-be-open-in-same-web-view-in-android) – Matthew Riches Jan 03 '14 at 13:07
  • 1
    @MatthewRiches Answers over there are not generic and cannot be implemented in osx. – user88975 Jan 03 '14 at 13:14

1 Answers1

1

Actually, your JavaScript is correct. I suspect you've created test html page to check it. 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. Use following code in your 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.

Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42