3

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?

rmaes4
  • 555
  • 9
  • 22
  • 1
    you can't http://stackoverflow.com/questions/1516715/executing-javascript-in-iframe-from-parent, please search first :) – Aram Kocharyan Apr 22 '12 at 04:19
  • oh, you can however access the parent from within the iframe http://stackoverflow.com/questions/935127/how-to-access-parent-iframe-from-javascript – Aram Kocharyan Apr 22 '12 at 04:20
  • @AramKocharyan Basically there is a website with a function. I can call this function by using "javascript:" in the URL bar. I would like to automate this, how can I accomplish this? – rmaes4 Apr 22 '12 at 04:42
  • Oh, it turns out I was mistaken: http://stackoverflow.com/questions/251420/invoking-javascript-in-iframe-from-parent-page – Aram Kocharyan Apr 23 '12 at 08:17

1 Answers1

1

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).

Bob Davies
  • 2,229
  • 1
  • 19
  • 28