Sara Ree
Sara Ree

Reputation: 3543

Best solution to access a function inside the iframe via URL

How can I access a function inside my iframe when I only can select the iframe via its URL. I mean I only can select the iframe using this:

const component = $(`iframe[src*='https://example.com/example.html']`); 

Here is a working code I'm using:

function executeIframeFunctionFromParent() {

  const component = $(`iframe[src*='https://example.com/example.html']`); // I only have the source url of the iframe and nothing else
  component.attr("id","mainComponentID");
  document.getElementById('mainComponentID').contentWindow.addStructures();

}

In the above code, I add an id to the iframe before accessing the function inside but, I wonder if there is a solution not to add an id to the iframe before accessing the function.

Note: the above code is working and there is no cross-domain iframe...

Upvotes: 0

Views: 31

Answers (1)

agrm
agrm

Reputation: 3852

The problem is that component is a jQuery object while contentWindow is a property on native DOM elements. One way to pull the DOM element from the jQuery object is simply adding [0] at the end of the variable name. So replace the last two lines of code with this:

component[0].contentWindow.addStructures();

Another way is to use the .prop() jQuery method, as @Taplar suggests:

component.prop('contentWindow').addStructures();

Upvotes: 1

Related Questions