spinners
spinners

Reputation: 2679

Call parent function that was written to parent from iFrame in IE8

I have an issue in IE8. I have an iframe as follows.

<!doctype html>
<html lang="en">
<head>
</head>

<body>
<script id="myscript">
function foo() { alert('foo'); }
</script>


(function () {
    var pdoc = parent.document;
    var dest = pdoc.head;
    var text = document.getElementById("myscript").textContent;

    var pscr = pdoc.createElement("script");
    pscr.textContent = text;
    dest.appendChild(pscr);

    parent.foo();
})();
</body>
</html>

The iframe copies the script to the parent and runs the function foo on the parent.

This works perfectly well on all the browsers I need it to except for IE 8. (This is not a cross domain issue)

I get "Object doesn't support this property or method"

Upvotes: 0

Views: 594

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Older IE doesn't have textContent. It has innerText, but for script elements you use text instead.

Separately, document.head isn't automatically provided on IE8; use document.getElementsByTagName('head')[0] instead.

With those two changes, this works on IE8, IE11, current Chrome, and current Firefox:

(function () {
    var pdoc = parent.document;
    var dest = pdoc.getElementsByTagName('head')[0];
    var script = document.getElementById("myscript");
    var prop = 'textContent' in script ? 'textContent' : 'text';
    var text = script[prop];

    var pscr = pdoc.createElement("script");
    pscr[prop] = text;
    dest.appendChild(pscr);
    parent.foo();
})();

Of course, doing this via text is only useful if you need the new foo function to close over the other window's global context. But presumably that's what you're trying to do...

Upvotes: 1

Related Questions