Consider we have an external URL http://xyz.com which has some links (for example, http://example.com/privacy-policy) that needs to be opened in the new tab. The solution is very simple-
<a href="http://example.com/privacy-policy" target="_blank">
Privacy Policy
</a>
This will work great in a normal browser. But when the link http://xyz.com is opened in a InAppBrowser (via Cordova WebView), and when the Privacy Policy link is clicked, the current WebView (where the example.com is opened) will be changed to http://example.com/privacy-policy and http://xyz.com will be unloaded. This is acceptable at various scenarios.
The above small JavaScript snippet can handle this scenario very well. Basically, Cordova's InAppBrowser plugin allows to accept the event posted from JavaScript code from the WebView (detailed can be read from here.
So the snippet checks if the webkit message handler is available in the webpage, if it is available (that means the link is opened in the in-app browser), we send a message to the Cordova app and then Cordova app can open the link to the system's default browser.
Otherwise, if webkit message handler is not available, it opens simply using window.open()
.
- Copy the
<script>
tag snippet from the be below file and paste it in your HTML page (where you want to open the exteral link). - Now, replace your links like
<a href="http://example.com/privacy-policy" target="_blank">
to<a href="#" onclick="return openInNewTab(http://example.com/privacy-policy)">
. - Ask your Cordova mobile app developer to handle the event and open the link in external browser using
InAppBrowser.addEventListener
.