帮助重构一小段识别用户引荐来源的Javascript代码

时间:2011-03-09 14:28:35

标签: javascript client-side referrer

我编写了以下一小段javascript(基于优秀的parseURI函数)来识别用户的来源。我是Javascript的新手,虽然下面的代码有效,但是想知道是否有更有效的方法来实现同样的结果?

try {
        var path = parseUri(window.location).path;

        var host = parseUri(document.referrer).host;
        if (host == '') {
                alert('no referrer');
                }

        else if (host.search(/google/) != -1 || host.search(/bing/) != -1 || host.search(/yahoo/) != -1) {
                alert('Search Engine');
                }
        else {
                alert('other');
                }
        } 

catch(err) {}

2 个答案:

答案 0 :(得分:2)

您可以使用其他搜索简化主机检查:

else if (host.search(/google|bing|yahoo/) != -1 {

我也很想在解压主机之前测试文件引荐来源,因为你的“没有推荐人”错误。

(我没试过这个)。

答案 1 :(得分:0)

我最终在很多项目中定义了一个名为set的函数。它看起来像这样:

function set() {
    var result = {};
    for (var i = 0; i < arguments.length; i++)
        result[arguments[i]] = true;
    return result;
}

一旦你得到了你正在寻找的主机名部分......

// low-fi way to grab the domain name without a regex; this assumes that the
// value before the final "." is the name that you want, so this doesn't work
// with .co.uk domains, for example
var domain = parseUri(document.referrer).host.split(".").slice(-2, 1)[0];

...您可以使用JavaScript的in运算符和我们在上面定义的set函数对列表中的结果进行优雅测试:

if (domain in set("google", "bing", "yahoo"))
    // do stuff

更多信息: