Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
帮助重构识别用户的一小段Javascript代码';s推荐源_Javascript_Client Side_Referrer - Fatal编程技术网

帮助重构识别用户的一小段Javascript代码';s推荐源

帮助重构识别用户的一小段Javascript代码';s推荐源,javascript,client-side,referrer,Javascript,Client Side,Referrer,我已经编写了以下一小段javascript(基于出色的函数)来识别用户的来源。我是Javascript新手,虽然下面的代码可以工作,但我想知道是否有更有效的方法来实现同样的结果 try { var path = parseUri(window.location).path; var host = parseUri(document.referrer).host; if (host == '') { alert('n

我已经编写了以下一小段javascript(基于出色的函数)来识别用户的来源。我是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) {}

您可以使用替代搜索简化主机检查:

else if (host.search(/google|bing|yahoo/) != -1 {
我还想在提取主机之前测试文档引用器,以防出现“无引用”错误


(我没有测试过这个)。

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

function set() {
    var result = {};
    for (var i = 0; i < arguments.length; i++)
        result[arguments[i]] = true;
    return result;
}
…您可以使用JavaScript的
in
操作符和上面定义的
set
函数,根据列表优雅地测试结果:

if (domain in set("google", "bing", "yahoo"))
    // do stuff
更多信息:


谢谢!我刚刚测试了你的建议,在提取主机之前测试文档引用者,它似乎有效!下面是更新后的代码:if(document.referer){var host=parseUri(document.referer).host;if(host.search(/google | bing | yahoo/)!=-1){alert('search Engine');}else{alert('other');}else{alert('direct');}小心。这也将符合
mygoogleclone.myevilsite.com
非常好的观点。你可以将谷歌(和其他网站)的正则表达式修改为类似“^www.google”(com | co…)$”的内容。尽管这需要仔细测试(同样,我还没有测试过)以确保它不会导致任何假阴性。我猜这取决于你所追求的检查有多可靠。
if (domain in set("google", "bing", "yahoo"))
    // do stuff