rmaes4
rmaes4

Reputation: 565

How to run an iFrame's script from the parent web page?

Ok so lets say I have a webpage, webpage B. Webpage B has a function called "test()". Now lets say I have another webpage, webpage A. Webpage A has an iFrame with the source of webpage B. How can I execute webpage B's "test()" function from webpage A?

Upvotes: 3

Views: 1069

Answers (1)

Bob Davies
Bob Davies

Reputation: 2282

You cannot 'directly' control the javascript of a page within an iframe by any code in the parent page.

If however you have the ability to change both pages, you can change 'page B' to run javascript based on parameters in it's query string.

In 'page A' Set the iframe src to something like:

http://mydomain.com/pageb.html?func=myfunc&param=foo&param2=bar

Then in 'page B' run some javascript like this:

function queryToLookup(query) {
    var lookup= {};
    var params= query.slice(1).split(/[&;]/);
    for (var i= 0; i<params.length; i++) {
        var ix= params[i].indexOf('=');
        if (ix!==-1) {
            var name= decodeURIComponent(params[i].slice(0, ix));
            var value= decodeURIComponent(params[i].slice(ix+1));
            if (!(name in lookup))
                lookup[name]= [];
            lookup[name].push(value);
        }
    }
    return lookup;
}

function myTestFunc(p1, p2) {
    alert('param 1 is ' + p1 + ' and p2 is ' + p2);
}

jQuery(document).ready(function() {
    var params = queryToLookup(location.search);
    switch(lookup['func'])
    {
        case 'myfunc': myTestFunc(params['param1'], params['param2']);
        case 'otherfunc': myTestFunc('someval', params['param1']);
        default: alert('No function requested');
    }
});

This is of course a very basic example, but can be adapted to do all kinds of crazy stuff. The limitation is that you can't really pass messages back to 'page A', although you 'could' (I think) adapt the technique in page A then call top.location = 'pagea.html?message=foo' (like how frame-breaking works).

Upvotes: 1

Related Questions