javascript window.open without http://

前端 未结 5 1839
独厮守ぢ
独厮守ぢ 2021-01-05 04:18

I have a small tool build with Delphi that collects url\'s from a file or from the clipboard, and than builds a file called test.htm with a content like this :



        
5条回答
  •  礼貌的吻别
    2021-01-05 05:12

    As you suggested, the only way is to add the http protocol to each URL which is missing it. It's a pretty simple and straightforward solution with other benefits to it.

    Consider this piece of code:

    function windowOpen(url, name, specs) {
        if (!url.match(/^https?:\/\//i)) {
            url = 'http://' + url;
        }
        return window.open(url, name, specs);
    }
    

    What I usually do is to also add the functionality of passing specs as an object, which is much more manageable, in my opinion, than a string, even setting specs defaults if needed, and you can also automate the name creation and make the argument optional in case it's redundant to your cause.

    Here's an example of how the next stage of this function may look like.

    function windowOpen(url, name, specs) {
        if (!url.match(/^https?:\/\//i)) {
            url = 'http://' + url;
        }
        // name is optional
        if (typeof name === 'object') {
            specs = name;
            name = null;
        }
        if (!name) {
            name = 'window_' + Math.random();
        }
        if (typeof specs === 'object') {
            for (var specs_keys = Object.keys(specs), i = 0, specs_array = [];
                    i < specs_keys.length; i++) {
                specs_array.push(specs_keys[i] + '=' + specs[specs_keys[i]]);
            }
            specs = specs_array.join(',');
        }
        return window.open(url, name, specs);
    }
    

提交回复
热议问题