安装应用程序的jQuery AJAX Cross-Origin检查

时间:2017-04-21 08:58:55

标签: jquery ajax

我想检查用户是否安装了我的应用,该应用是使用协议' myapp://'创建的。

点击按钮,我想检查用户是否安装了应用程序,如果有,请将浏览器位置设置为将打开或至少提示打开应用程序的应用程序URL方案,否则,将用户引导到另一个页面。

这是我到目前为止: -

<div>
    <p>Do you have my app installed?</p>
    <button type="button" id="appinstalled">Yes</button>
</div>
jQuery("#appinstalled").click(function() {
    var addr = "myapp://currentpage";
    jQuery.ajax({
        type: 'HEAD',
        url: addr,
        success: function() {
            document.location.href = addr;
        },
        error: function() {
            document.location.href = "http://example.com/app-not-installed";
        }
    });
});

不幸的是,由于CORS失败了: -

  

XMLHttpRequest无法加载myapp://example.com/index.php。只有HTTP支持跨源请求。

所以这显然不起作用。

我可以使用替代方法吗?我的网站/应用程序将在主要无法访问互联网的环境中使用,因此我无法将用户定向到相关的应用商店。

1 个答案:

答案 0 :(得分:0)

我遇到了类似(不准确)的问题。这对我有用:

var url = "myapp://currentpage";
var method = "GET";
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    // CORS not supported.
    xhr = null;
}

if (!xhr) {
    alert('CORS not supported');
    return;
}
// Response handlers.
xhr.onload = function () {
    //Whoo Hoo it worked
};
xhr.onerror = function (data) {
    //A million curses it did not
};
xhr.send();

注意:无论我做什么,它都无法直接使用ajax。我需要直接使用XMLHttpRequest。

ALSO :您需要在当前页面的位置正确设置目录。您需要更改该目录中的.htaccess文件以获取apache服务器以允许访问所有源。这是大量记录在这里,所以我不会再这样做了。但是,如果您使用的是Windows服务器,则必须更改目录中的web.config文件

的web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>