mdixon18
mdixon18

Reputation: 1219

How to allow iframe to access Element.prototype

I have created prototypes such as hasClass() so i can call e.target.hasClass('className');. Now, when i call the prototype it works, however I have an iframe on my page which I go in and out of all the time as I am working on a page builder. However, if I am referring to an element within the iframe the prototype function doesn't exist to the element.

How can I get the Element.prototype functions to work within both the parent and the iframe?

Upvotes: 0

Views: 827

Answers (2)

charlietfl
charlietfl

Reputation: 171669

You need to access the iframe window inside a load event handler and can do something like the following:

var frame = document.getElementById('ifrm');
frame.onload = function() {
  var win = this.contentWindow || this.contentDocument;
  win.Element.prototype.test = function() {
    this.innerHTML = 'Iframe Prototype content'
  }
  win.document.getElementById('heading').test()

}

So if you were to wrap all your new prototype properties into a function you could call that in both the main window context and the frame window context

DEMO

Upvotes: 2

Quentin
Quentin

Reputation: 943686

Each window has its own Element object. You need to add your function to the prototype of the Element belonging to the iframe as well as the parent frame's.


Alternatively, don't add your own function. Use the standard one:

e.target.classList.contains("className");

Upvotes: 0

Related Questions