0

I would like to globally redefine a createElement method, but unfortunately it only works in a main document, and is ignored in iframes. Let's take this example code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
    old_createElement = document.createElement;
    document.createElement = function(el_type) {
        new_el = old_createElement.call(this, el_type);
        new_el.style.color="red";
        return new_el;
    };
</script>
</head>
<body bgcolor="white">
<iframe id="iframe1"></iframe>

<script type="text/javascript">
 window.setTimeout(function(){
    iframe_el = document.getElementById("iframe1").contentDocument.createElement("div");
    iframe_el.innerHTML = 'inside iframe';
    document.getElementById("iframe1").contentDocument.body.appendChild(iframe_el);
 },50);

 no_iframe_el=document.createElement('div');
 no_iframe_el.innerHTML = 'outside of iframe';
 document.body.appendChild(no_iframe_el);
</script>

</body>
</html>

When i open in in a browser, the element created in a main document has red color, as expected, but the one in the iframe is black.

The problem is that I only have control on the script contained in the HEAD section of the document. In other words, i don't know how many iframes there will be later on in the HTML source, or how they will be names, or if they are added via user's Javascript.

My question is: how can i change the method globally, so all elements created in iframes also use this new style?

Thanks a lot!

2
  • 1
    each iframe has it's own scope/global scope/dom/css/whatever so your document.createElement is not available there Commented Apr 10, 2016 at 8:35
  • answer is: no. because: security. you can't write your viruses or whatever Commented Apr 10, 2016 at 8:36

1 Answer 1

1

Each frame has it's own separate Javascript context. If you want to change that frame's context, you have to do it specifically for that frame.

In your specific example, each frame has its own document object so it should be no surprise that each document has its own .createElement property.

You cannot generically change things in a way that will affect all frames. And, in fact if it's a cross-origin frame, you can't change it at all.

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.