Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 239
user603007 Avatar asked Nov 01 '11 05:11

user603007


3 Answers

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.

like image 188
Marwan Avatar answered Oct 20 '22 10:10

Marwan


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
like image 1
codifier Avatar answered Oct 20 '22 11:10

codifier


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
like image 1
Matimu-Mbino Avatar answered Oct 20 '22 11:10

Matimu-Mbino