PhoneGap:如何在默认浏览器中打开外部链接(应用程序外部)

27

我正在尝试从一个PhoneGap应用程序中在Safari(iPhone上)中打开链接。我使用的是PhoneGap 3.1.0 版本,并使用PhoneGap Build来构建应用程序。

页面上有两个链接(在www/index.html中显示)。这两个链接都在PhoneGap应用程序内部打开。我可以看到PhoneGap已经正确加载,因为alert('device ready!');被触发了。

我需要更改什么才能在默认浏览器中(应用程序外部)打开链接?

www/config.xml 文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0" id="com.company.appname" version="0.0.3">
  <name>AppName</name>
  <description>description</description>
  <author href="http://www.example.com/" email="hello@example.com">
    Company
  </author>
  <preference name="phonegap-version" value="3.1.0" />
  <preference name="orientation" value="portrait" />
  <preference name="stay-in-webview" value="false" />

  <gap:plugin name="org.apache.cordova.inappbrowser" version="0.2.3" />
  <gap:plugin name="org.apache.cordova.dialogs" version="0.2.2" />
  <gap:plugin name="com.phonegap.plugins.pushplugin" version="2.0.5" />

  <plugins>
    <plugin name="InAppBrowser" value="CDVInAppBrowser" />
  </plugins>

  <feature name="InAppBrowser">
    <param name="ios-package" value="CDVInAppBrowser" />
  </feature>
  <access origin="*" />
</widget>

www/index.html文件的外观如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <title>Test application</title>
</head>
<body>
  <a href="#" onclick="openUrl('http://www.google.com/'); return false;">Link test 1</a>
  <a href="#" onclick="window.open('http://www.google.com/', '_system', 'location=yes'); return false;">Test link 2</a>

  <script src="phonegap.js"></script>
  <script src="cordova.js"></script>
  <script src="js/jquery-1.9.1.js"></script>
  <script type="text/javascript">
    function openUrl(url) {
      alert("open url: " + url);
      window.open(url, '_blank', 'location=yes');
    }

    function onDeviceReady() {
      alert('device ready!');
    }
    $(function() {
        document.addEventListener("deviceready", onDeviceReady, true);
    });
  </script>
</body>
</html>

这是项目结构:

├── platforms
├── plugins
│   └── org.apache.cordova.inappbrowser
│       ├── LICENSE
│       ├── package.json
│       ├── plugin.xml
│       ├── README.md
│       ├── RELEASENOTES.md
│       ├── src
│       │   ├── android
│       │   │   ├── InAppBrowser.java
│       │   │   └── InAppChromeClient.java
│       │   ├── blackberry10
│       │   │   └── README.md
│       │   ├── ios
│       │   │   ├── CDVInAppBrowser.h
│       │   │   └── CDVInAppBrowser.m
│       │   └── wp
│       │       └── InAppBrowser.cs
│       └── www
│           ├── InAppBrowser.js
│           └── windows8
│               └── InAppBrowserProxy.js
├── README.md
└── www
    ├── config.xml
    ├── cordova.js
    ├── index.html
    ├── js
    │   └── jquery-1.9.1.js
    └── phonegap.js

这里有什么问题吗....??? - Mumthezir VP
@mvp 我猜在Safari浏览器中链接无法打开。 - Jacob
在你的代码中,你正在尝试使用InAppBrowser,它会在应用程序内部打开另一个窗口。你想要在浏览器中打开,对吗? - Mumthezir VP
是的,我想要在默认浏览器中打开外部链接。而不是在应用程序内部打开。 - Martin
你有解决方案吗? - Piyush
显示剩余8条评论
16个回答

17

这是我在 Cordova/Phonegap 3.6.3 中解决问题的方法:

安装 inappbrowser Cordova 插件:

cordova plugin add org.apache.cordova.inappbrowser

我希望让我的PhoneGap应用尽可能类似于标准网页:我想通过在链接上添加target="_blank"来使其在外部页面中打开。

这是我的实现方式:

$("a[target='_blank']").click(function(e){
  e.preventDefault();
  window.open($(e.currentTarget).attr('href'), '_system', '');
});

所以我只需要使用以下链接即可:

<a href="http://www.example.com" target="_blank">Link</a>

1
这个解决方案是有效的,但如果我想要使用另一个插件Crosswalk https://crosswalk-project.org/ ,而不是使用默认的webview,Crosswalk作为默认的webview,那么如果我使用inappbrowser插件,就没有使用Crosswalk插件的意义了。我该怎么办? - Shersha Fn

10

这个怎么样?

<a href="#" onclick="window.open(encodeURI('http://www.google.com/'), '_system')">Test link 2</a>

编辑:

这可能与以下内容有关: 如何在onclick事件中调用多个JavaScript函数?

我在想,怎么样:

添加到代码中:

$(".navLink").on('tap', function (e) {
    //Prevents Default Behavior 
    e.preventDefault();
    // Calls Your Function with the URL from the custom data attribute 
    openUrl($(this).data('url'), '_system');
});

那么:

<a href="#" class="navLink" data-url="http://www.google.com/">Go to Google</a>

这个链接在我的iPhone上没有任何反应 - 因为onclick没有返回false来防止它跟随href =“#”。当我添加return false(像这样:{{link1:Test link 2}})时,Google会在应用程序内部打开:http://i.imgur.com/xKj1XZB.png - Martin
更改以防止默认行为。 - Red2678
正如你可能注意到的那样,我在我的原始评论中发布的JavaScript中有一个openUrl方法。我看到你用两个参数调用了openUrl,所以我假设你正在调用另一个方法,并注释掉了我的openUrl方法(它只需要一个参数)。当我测试时没有任何反应。 - Martin
你的 openURL 函数只接受一个参数。function openUrl(url) { alert("打开链接:" + url); window.open(url, '_system'); } - Red2678
1
你应该将其更改为“_system”,并删除位置参数。 - Red2678
显示剩余3条评论

9

安装插件时,您应使用gap:plugin标签和完全限定的ID在config.xml中进行配置:

<gap:plugin name="org.apache.cordova.inappbrowser" />

如此文档所述 在这里


我有这行代码:<gap:plugin name="org.apache.cordova.inappbrowser" version="0.2.3"/>,我可以看到它已经添加到PhoneGap Build的插件选项卡中。http://i.imgur.com/e90CzMR.png。我需要移除版本号吗? - Martin
1
据我所知,这并不会在默认浏览器中打开链接。它会在InAppBrowser中打开。那是不同的。例如,当我在Facebook应用程序中点击链接时,它会在InAppBrowser中打开链接。如果然后有选择“在Safari中打开”。这就是我要找的第二个功能。不是InAppBrowser。 - gman
@gman,你需要将“_system”参数传递给window.open链接,以使用系统浏览器而不是inappbrowser。请参见上面Red2678的解决方案。 - wildabeast

7

我正在使用 Cordova 6.0,以下是我的解决方案:

1:安装这个 Cordova 插件。

cordova plugin add cordova-plugin-inappbrowser

2:在HTML中添加以下打开链接。

<a href="#" onclick="window.open('https://www.google.com/', '_system', 'location=yes');" >Google</a>

第三步是最重要的一步,因为我曾经遇到过很多问题: 下载cordova.js文件并将其粘贴到www文件夹中。 然后在index.html文件中引用它。

<script src="cordova.js"></script>

这个解决方案适用于Android和iPhone两种环境。

1
确保已添加 cordova.js 脚本,这为我解决了这个问题。 - jla

3

试试下面的例子。

<a class="appopen" onClick="OpenLink();">Sign in</a>


<script>
function OpenLink(){
    window.open("http://www.google.com/", "_system");
}
</script>

如果您正在使用PhoneGap 3.1或更高版本,请在config.xml中添加以下行:
<gap:plugin name="org.apache.cordova.inappbrowser" />

请查看此链接。可能是这个链接的重复问题 https://dev59.com/vGkv5IYBdhLWcg3w8FOY#17849217 - Nijil Nair
@NijilNair 我添加了以下代码:function openlink2() { var ref = window.open(encodeURI("http://www.google.com/"), '_system', 'location=no'); } 并添加了一个链接:<a class="appopen" href="#" onClick="openlink2(); return false;">Another link</a>。但是,Google 仍然在应用程序内部打开:http://i.imgur.com/xKj1XZB.png - Martin
$(document).on("click", "#div_id", function() { var yourUrl = 'google.com/'; var ref = window.open(encodeURI(yourUrl), '_system', 'location=no'); });尝试使用<div>代替<a>。由于您没有传递任何href,因此需要有一个<a>。 - Nijil Nair
我做那件事时什么也没发生。在使用PhoneGap构建之前,我已经在浏览器中进行了测试(成功),所以我知道这不是JavaScript错误。 - Martin
很遗憾,截止日期已经过去了,所以我们必须在应用程序中删除该功能。 :-( - Martin
显示剩余2条评论

3
我曾经遇到和你一样的问题,解决方法是在我将使用InAppBrowser的所有页面的<head>中包含phonegap.js文件。
你的代码都没问题!唯一需要添加的是:在你的index.html<head>部分加入<script src="phonegap.js"></script>
这有点奇怪,因为Phonegap在插件文档部分中说:
“如果插件利用了js-module元素指向cordova加载插件JavaScript,则不需要<script>引用来加载插件。核心cordova插件就是这种情况。”
而InAppBrowser是一个核心cordova插件。但由于某种奇怪的原因,在0.3.3版本中不工作,直到你包含phonegap.js文件。
注意:我发现了一个错误。有些人说你必须包含3个文件:phonegap.js, cordova.jscordova_plugins.js。但当我包含这三个文件时,我的应用程序在iOS 7上运行良好,但在iOS 6上忽略了插件的使用(使用:Cordova 3.3.0 + Phonegap Build + InAppBrowser 0.3.3)。
你可以在我的这个SO问题中看到更多信息。
希望这能帮助你!

2

虽然回答晚了,但也许对某些人有帮助。以下是我在基于Cordova的iOS和Android应用程序中使用的工作代码。要在默认浏览器(Safari或Google)中打开外部链接:

1)确保您安装了inAppBrowser插件

cordova plugin add cordova-plugin-inappbrowser --save

2) 添加到 device.js

function openURL(urlString){
  let url = encodeURI(urlString);
  window.open(url, '_system', 'location=yes');
}

3) 创建新链接

<a href="#" onClick="openURL('http://www.google.com')">Go to Google</a>

1

对于iOs,在您的MainViewController.m中执行以下操作:

- (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    if (![url isFileURL] && navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
            return NO;
        }
    } 

    return [super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType]; 
}

编辑: 对于Android,在CordovaWebViewClient.java文件中,在shouldOverrideUrlLoading方法中执行以下操作:

public boolean shouldOverrideUrlLoading(WebView view, String url) {
          if(/*check if not external link*) {
            view.loadUrl(url);
          } else {
            //prepend http:// or https:// if needed
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(i);
          }
          return true;
        }

1
我将pastullo的答案进行了改编,以适用于可能在cordova InAppBrowser中打开的WebApp,但也可以作为普通Web应用程序(例如用于测试):
function initOpenURLExternally() {
    $("a[target='_blank'],a[target='_system']").each(function (i) {
        var $this = $(this);
        var href = $this.attr('href');
        if (href !== "#") {
            $this
                .attr("onclick", "openURLExternally(\"" + href + "\"); return false;")
                .attr("href", "#");
        }
    });
}

function openURLExternally(url) {
    // if cordova is bundeled with the app (remote injection plugin)
    log.trace("openURLExternally: ", url);
    if (typeof cordova === "object") {
        log.trace("cordova exists ... " + typeof cordova.InAppBrowser);
        if (typeof cordova.InAppBrowser === "object") {
            log.trace("InAppBrowser exists");
            cordova.InAppBrowser.open(url, "_system");
            return;
        }
    }

    // fallback if no cordova is around us:
    //window.open(url, '_system', '');
    window.open(url, '_blank', '');
}

1

这个在iOS上完美地运行。

如上面的链接所提到的:

1- 使用以下命令安装插件:

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git 

2- 在HTML文件中,根据需要使用以下之一:

window.open(‘http://example.com’, ‘_system’);   Loads in the system browser 
window.open(‘http://example.com’, ‘_blank’);    Loads in the InAppBrowser
window.open(‘http://example.com’, ‘_blank’, ‘location=no’); Loads in the InAppBrowser with no location bar
window.open(‘http://example.com’, ‘_self’); Loads in the Cordova web view 

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