使用JavaScript从iPhone Web应用程序打开外部页面?

时间:2012-01-05 07:11:27

标签: javascript hyperlink iphone-web-app iphone-standalone-web-app

我已经建立了一个移动网站 - 一个针对手持设备优化的网站。如果您使用的是iPhone,则启动Safari并转到站点URL以使用此Web应用程序。通过将其添加到主屏幕,它也可以作为iPhone web app运行。所以它不是原生的iPhone应用程序 - 它是一个移动网页。

如果您选择将此移动网页作为iPhone网络应用程序运行(通过将其添加到主屏幕),则您不在常规Safari界面中。如果用户点击链接到外部网站,您将离开网络应用程序并在Safari中打开该链接。另一方面,如果您使用JavaScript来更改位置,则会在网络应用中打开链接,而不是在Safari中打开。

现在我正在寻找一种使用JavaScript从iPhone网络应用程序在Safari中打开链接的方法。我已经尝试过window.location.href但是因为它是JavaScript,你会留在网络应用程序中。

提前致谢!

2 个答案:

答案 0 :(得分:0)

我也在努力解决这个问题。我在打开外部链接而不是Javascript时默认使用基本HTML - 这似乎强制它在另一个浏览器中打开。我只是在里面用链接写一个div,或者在.html文件中使用Javascript或static。

我的实施示例,检查用HTML编写的非现场链接的“关于”页面:http://4drillsbrewery.com/tools

(请不要判断代码,这只是为了习惯Dashcode而写的玩具,而不是编程项目!谢谢)。我会关注这个帖子,希望有人有更好的方法。

答案 1 :(得分:0)

我很欣赏这在所有情况下都没有帮助但是提供的javascript代码源于用户生成的超链接点击有这个解决方案......

$("a.someHyperLink").click(function () {
    var url = doJavascriptStuffToGenerateTheDynamicUrl();
    $(this).prop("href", url);
    return true; // return true so the click propagates and the new href is followed
});

您可以进一步扩展此功能,以便在Safari正常浏览网站时以及作为独立应用程序时都能正常工作。

$("a.someHyperLink").click(function () {
    var url = doJavascriptStuffToGenerateTheDynamicUrl();
    if (window.navigator.standalone) {
        // We are within the context of an iPhone standalone/fullscreen/homescreen app
        // Change the href and return true so that we leave the standalone app and the URL is opened in a new window in Safari
        $(this).prop("href", url);
        return true;
    } else {
        // Website is open in a browser normally
        // Open the URl in a new browser window
        window.open(url);
        return false; // Return false so the href isn't followed
    }
});