Help refactor a small piece of Javascript code which identifies user's referrer source

笑着哭i 提交于 2019-12-25 16:03:19

问题


I've written the following small piece of javascript (Based on the excellent parseURI function) to identify where the user originated from. I am new to Javascript, and although the code below works, was wondering if there is a more efficient method of achieving this same result?

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) {}

回答1:


You can simplify the host check using alternative searches:

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

I'd also be tempted to test document referrer before extracting the host for your "no referrer" error.

(I've not tested this).




回答2:


I end up defining a function called set in a lot of my projects. It looks like this:

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

Once you've got the portion of the hostname that you're looking for...

// 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];

...you can elegantly test your result against a list using JavaScript's in operator and the set function we defined above:

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

More info:

  • http://laurens.vd.oever.nl/weblog/items2005/setsinjavascript/


来源:https://stackoverflow.com/questions/5247207/help-refactor-a-small-piece-of-javascript-code-which-identifies-users-referrer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!