Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

We found unexpected behavior with URL object in safari. When you convert URL to string it will add 0 port(:0) if you set the port property to an empty string. e.g.

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/"

enter image description here

From spec I see:

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

So is it bug or feature in safari?

like image 214
Alexandr Vysotsky Avatar asked Nov 07 '22 11:11

Alexandr Vysotsky


1 Answers

I've also run into this. It's Web Kit Bug 127958 and at the time of writing almost 6 years old. The obvious workaround is to simply avoid assigning empty strings.

For example, if you have code like this:

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

You could instead do this:

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 ];
    }
}
like image 173
akirk Avatar answered Nov 12 '22 19:11

akirk