diff --git a/lib/internal/url.js b/lib/internal/url.js index da4eb07a815c45..c286e49aa14294 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -195,12 +195,7 @@ function onParseSearchComplete(flags, protocol, username, password, if (flags & binding.URL_FLAGS_FAILED) return; const ctx = this[context]; - if (query) { - ctx.query = query; - ctx.flags |= binding.URL_FLAGS_HAS_QUERY; - } else { - ctx.flags &= ~binding.URL_FLAGS_HAS_QUERY; - } + ctx.query = query; } function onParseHashComplete(flags, protocol, username, password, @@ -487,13 +482,15 @@ Object.defineProperties(URL.prototype, { if (!search) { ctx.query = null; ctx.flags &= ~binding.URL_FLAGS_HAS_QUERY; - this[searchParams][searchParams] = {}; - return; + } else { + if (search[0] === '?') search = search.slice(1); + ctx.query = ''; + ctx.flags |= binding.URL_FLAGS_HAS_QUERY; + if (search) { + binding.parse(search, binding.kQuery, null, ctx, + onParseSearchComplete.bind(this)); + } } - if (search[0] === '?') search = search.slice(1); - ctx.query = ''; - binding.parse(search, binding.kQuery, null, ctx, - onParseSearchComplete.bind(this)); initSearchParams(this[searchParams], search); } }, @@ -611,9 +608,11 @@ function update(url, params) { } } -// Reused by the URL parse function invoked by -// the href setter, and the URLSearchParams constructor function initSearchParams(url, init) { + if (!init) { + url[searchParams] = []; + return; + } url[searchParams] = getParamsFromObject(querystring.parse(init)); } diff --git a/test/parallel/test-whatwg-url-searchparams.js b/test/parallel/test-whatwg-url-searchparams.js index 8b9e65123d9506..b3885a48be91e7 100644 --- a/test/parallel/test-whatwg-url-searchparams.js +++ b/test/parallel/test-whatwg-url-searchparams.js @@ -20,6 +20,10 @@ assert(sp.has('a')); assert.strictEqual(sp.get('a'), '[object Object]'); sp.delete('a'); assert(!sp.has('a')); + +m.search = ''; +assert.strictEqual(sp.toString(), ''); + values.forEach((i) => sp.append('a', i)); assert(sp.has('a')); assert.strictEqual(sp.getAll('a').length, 6);