Safari 将 URL 中的 ''(空字符串)转换为 0

Safari convert '' (empty string) to 0 in URL

我们发现 URL 对象在 Safari 浏览器中出现意外行为。当您将 URL 转换为字符串时,如果您将端口 属性 设置为空字符串,它将添加 0 端口(:0)。例如

let url = new URL('https://www.example.com');
url.port = '';
console.log(url.toString()); // expected "https://www.example.com/", actual "https://www.example.com:0/"

来自spec我看到:

If the given value is the empty string, then set context object’s URL's port to null.

那么这是 Safari 中的错误还是功能?

我也 运行 喜欢这个。它是 Web Kit Bug 127958,在撰写本文时已经将近 6 岁了。明显的解决方法是简单地避免分配空字符串。

例如,如果您有这样的代码:

template = new URL( template_url );
result = new URL( input_url );
for ( part in template ) {
    result[ part ] = template[ part ] ?? result[ part ];
}

您也可以这样做:

template = new URL( template_url );
result = new URL( input_url );
for ( part in template ) {
    if ( template[ part ] && template[ part ] !== result[ part ] ) {
        result[ part ] = template[ part ];
    }
}