Posts Tagged ‘iframe’

I recently found myself in a scenario where I needed to copy the contents of an iframe to another. Madness you say? Hold on… there is a method to my madness. I am using Wymeditor to help manage my html fields/properties on a form. The client requested that the user should be able to import recently entered contents in a similar field on the same form. When these contents are “imported” only a certain amount of characters should be used. Almost like a short version (synopsis) of another field.

What does this have to do with Iframes I hear you ask? Well, Wymeditor uses an Iframe to box its functionality and mask it as a textarea.
After much searching I came up with the following:

$("#importFromFull").click(function(e) {
        e.preventDefault();
        var text = $("#postBodyTab .wym_iframe iframe")
            .contents()
            .find('body')
            .html();

        $("#longSynopsisTab .wym_iframe iframe")
            .contents()
            .find('body')
            .html(text.substr(0, 255));
    });

Thus, the function for retrieving the contents of any iframe is:

$("#myIframe")
            .contents()
            .find('body')
            .html();

(Please note, this will only work if both iframes are on the same domain. There are security issues for manipulating an iframe’s content)