Shamoon
Shamoon

Reputation: 43491

URLSearchParams returns empty from within an iframe

My iframe is:

<iframe src="iframe.html?name=%1A%C3%A9%C2%AB%C2%A1%C2%A7O%C2%AE%C2%87nr%C3%9D" allowtransparency="allowtransparency" allowfullscreen="allowfullscreen" style="width: 100%; height: 100%; margin: 0; padding: 0; z-index: 9999; position: fixed; left: 0; top: 0; border: 0;"></iframe>

And from within iframe.html, I'm doing:

    let urlParams = new URLSearchParams(document.location.search)
    console.log(urlParams)

However, this always returns URLSearchParams {}__proto__: URLSearchParams

Empty.

What am I doing wrong?

Upvotes: 2

Views: 7281

Answers (1)

Andrey
Andrey

Reputation: 4050

URLSearchParams is not a plain object, so you need to use methods to get params, for example

console.log(urlParams.get('name'));

All methods are:

This interface doesn't inherit any methods.

URLSearchParams.append()

Appends a specified key/value pair as a new search parameter.

URLSearchParams.delete()

Deletes the given search parameter, and its associated value, from the list of all search parameters.

URLSearchParams.entries()

Returns an iterator allowing iteration through all key/value pairs contained in this object.

URLSearchParams.forEach()

Allows iteration through all values contained in this object via a callback function.

URLSearchParams.get()

Returns the first value associated with the given search parameter.

URLSearchParams.getAll()

Returns all the values associated with a given search parameter.

URLSearchParams.has()

Returns a Boolean indicating if such a given parameter exists.

URLSearchParams.keys()

Returns an iterator allowing iteration through all keys of the key/value pairs contained in this object.

URLSearchParams.set()

Sets the value associated with a given search parameter to the given value. If there are several values, the others are deleted.

URLSearchParams.sort()

Sorts all key/value pairs, if any, by their keys.

URLSearchParams.toString()

Returns a string containing a query string suitable for use in a URL.

URLSearchParams.values()

Returns an iterator allowing iteration through all values of the key/value pairs contained in this object.

MDN Reference

Upvotes: 9

Related Questions