5

$(selector).click() results in nothing happening.
this answer works in the browser console with the javascript context set to the iframe, but not the main page: simulateMouseClick($("iframe").contents().find(selector)) results in:

Uncaught TypeError: targetNode.dispatchEvent is not a function
at triggerMouseEvent (:5:20)
at :8:9
at Array.forEach ()
at simulateMouseClick (:7:52)
at :1:1

$("iframe").contents().find(selector).text() gives me what's expected so it's the correct element.

how can I achieve this?

Edit: adding this as people apparently can't read:
$("iframe").contents().find(selector).click()
has absolutely no effect as .click() does not simulate a REAL mouse click.

Flutter Shy
  • 51
  • 1
  • 3

2 Answers2

2

With jQuery :

$("iframe").contents().find(selector).click();

With Vannila JS :

Using window.frames gives you access to the iframes' window object, as mentionned in the Mozilla doc

You can use this object to find elements in the iframe and use them in your script. For example :

  var iframeWindow = window.frames[0];
  var element = iframeWindow.document.getElementsByClassName("selector")[0];
  element.click();
AllirionX
  • 1,073
  • 6
  • 13
  • 2
    someone clearly barely read the question, I have no problem getting the element, a simple `.click()` does not work, it has absolutely no effect, the only method I've found that does isn't working when done from the main page. – Flutter Shy Nov 14 '18 at 14:54
  • I just tried with Vanilla JS by replacing the element.click() with simulateMouseClick(element) to click on a link in an iframe, and it works. I am pretty sure you could also do it in jQuery with simulateMouseClick($("iframe").contents().find(selector)[0]) . But even though it might not be "real" click, .click() should at least trigger the click event. https://www.w3schools.com/code/tryit.asp?filename=FX9452XNM1SB May be you have other issues ? Are you dealing with crossdomain iframes or do you have several libraries loaded (jquery and prototype for example). – AllirionX Nov 14 '18 at 17:02
0

Get the element inside your jQuery Object, and use the vanillaJS .click() method:

$("iframe").contents().find(selector)[0].click();

That's it.

PS: I know this is an old question, but I had the same problem and solved it that way :)

Socrapop
  • 196
  • 1
  • 9