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?

4

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.