Cordova,为什么需要 InAppBrowser 插件才能在系统浏览器中打开链接

2024-05-08

我有一个 Cordova 应用程序,它是一个带有单个 HTML 文件的单页应用程序。

所有链接都应在系统浏览器中打开。我不需要“嵌入式”InAppBrowser,而是真正的本机系统/外部浏览器。

我们到处都可以找到使用 InAppBrowser 的代码示例,例如:

window.open('http://apache.org', '_system');

但是为什么我们需要安装 InAppBrowser,即使我们甚至不打算使用嵌入式浏览器?

有人能真正解释一下关于链接目标的 WebView 的行为吗?目前还不清楚它应该做什么target=_blank,但除了打开一个新的浏览器窗口之外,我看不出它还能做什么。

请注意,问题似乎只出现在 iOS 上,因为 Android(带有 Crosswalk 插件)使用target=_blank似乎总是工作正常并在新的本机浏览器窗口中打开。


所以我用我所发现的来回答我自己的问题。 注意我只处理iOS 和 Android(使用 Crosswalk 插件)科尔多瓦5.1.1,并且可能不适用于其他平台/版本。

需要 InAppBrowser

即使您不需要嵌入式浏览器,也需要 InAppBrowser 插件。这使得_system目标可用,触发本机插件代码打开系统/外部浏览器。

因此,该插件似乎在某种程度上是一个“二合一”插件:它允许使用嵌入式浏览器+它允许安全地强制外部系统浏览器打开。

目前尚不清楚默认的 WebView 行为应该与什么相关_blank链接(如果它以任何方式标准化为 WebViews),但我发现没有这个插件或本机代码就无法在 iOS 上打开外部浏览器。

Opening _self在 Web 视图中,以及_blank在本机浏览器中

如果像我一样你不关心嵌入式浏览器,而只是想打开所有_blank目标是现有应用程序中的本机外部浏览器,无需太多痛苦(特别是如果该应用程序也是移动网站......),您可以在应用程序的开头运行以下代码:

    function openAllLinksWithBlankTargetInSystemBrowser() {
        if ( typeof cordova === "undefined" || !cordova.InAppBrowser ) {
            throw new Error("You are trying to run this code for a non-cordova project, " +
                    "or did not install the cordova InAppBrowser plugin");
        }

        // Currently (for retrocompatibility reasons) the plugin automagically wrap window.open
        // We don't want the plugin to always be run: we want to call it explicitly when needed
        // See https://issues.apache.org/jira/browse/CB-9573
        delete window.open; // scary, but it just sets back to the default window.open behavior
        var windowOpen = window.open; // Yes it is not deleted !

        // Note it does not take a target!
        var systemOpen = function(url, options) {
            // Do not use window.open becaus the InAppBrowser open will not proxy window.open
            // in the future versions of the plugin (see doc) so it is safer to call InAppBrowser.open directly
            cordova.InAppBrowser.open(url,"_system",options);
        };


        // Handle direct calls like window.open("url","_blank")
        window.open = function(url,target,options) {
            if ( target == "_blank" ) systemOpen(url,options);
            else windowOpen(url,target,options);
        };

        // Handle html links like <a href="url" target="_blank">
        // See https://issues.apache.org/jira/browse/CB-6747
        $(document).on('click', 'a[target=_blank]', function(event) {
            event.preventDefault();
            systemOpen($(this).attr('href'));
        });
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Cordova,为什么需要 InAppBrowser 插件才能在系统浏览器中打开链接 的相关文章

随机推荐