user603007
user603007

Reputation: 11794

how to get the querystring from a parent page?

i am using an iframe ipage in my parentpage. I would like to get the querystring in javascript of the parentpage?

Upvotes: 10

Views: 25273

Answers (3)

Matimu-Mbino
Matimu-Mbino

Reputation: 11

ES6 implementation:

export const getQueryParameters = () => {
    const queryStringKeyValue = window.parent.location.search.replace('?', '').split('&');
    return queryStringKeyValue.reduce((acc, curr) => {
        const [key,value] = curr.split('=')
        return {
            ...acc,
            [key]: value
        }
    }, {})
}

Usage:

getQueryParameters().name

Upvotes: 1

codifier
codifier

Reputation: 31

nice answer from @Marawan. - if it helps anyone... I extended this to choose the target as a parameter (self / parent)

function getQueryString(target) {
    if ( target == 'parent' ) {
        var queryStringKeyValue = window.parent.location.search.replace('?', '').split('&');
    }
    else {
        var queryStringKeyValue = window.location.search.replace('?', '').split('&');
    }

    var qsJsonObject = {};
    if (queryStringKeyValue != '') {
        for (i = 0; i < queryStringKeyValue.length; i++) {
            qsJsonObject[queryStringKeyValue[i].split('=')[0]] = queryStringKeyValue[i].split('=')[1];
        }
    }
    return qsJsonObject;
}

eg.

getQueryString('parent').id;    // get iframe parent url ?id=foo
getQueryString().id;    // get this url ?id=foo

Upvotes: 1

Marwan
Marwan

Reputation: 2402

I suggest to you to use my favourite function:

 function getQueryString() {
                var queryStringKeyValue = window.parent.location.search.replace('?', '').split('&');
                var qsJsonObject = {};
                if (queryStringKeyValue != '') {
                    for (i = 0; i < queryStringKeyValue.length; i++) {
                        qsJsonObject[queryStringKeyValue[i].split('=')[0]] = queryStringKeyValue[i].split('=')[1];
                    }
                }
                return qsJsonObject;
            }

Just call it from the child window like this and act with the query string as an object.

For example if you have the query string ?name=stack and you want to get it, try:

getQueryString().name

This will return stack.

Upvotes: 17

Related Questions