0

How can I get the class of an element clicked upon in an iframe?

HTML:

<input id="tag" type="text">

<iframe id="framer" src="SameDomainSamePort.html"></iframe>

JS:

$(document).ready(function () {
    $("iframe").each(function () {
        //Using closures to capture each one
        var iframe = $(this);
        iframe.on("load", function () { //Make sure it is fully loaded
            iframe.contents().click(function (event) {
                iframe.trigger("click");
            });
        });

        iframe.bind("click", function(e) {
            // always returns the iframe rather than the element selected within the iframe...
            $("#tag", window.top.document).val($(e)[0].target.className);
            return false;
        });
    });
});

Would it be easier to inject js?

And could I add css as well?

All help is appreciated!

Luc Laverdure
  • 1,366
  • 2
  • 16
  • 33
  • Are there any console errors? Perhaps try `iframe.contents().find("#someContainer").on("click",function (event) {` and use `on` instead of `bind` - also the load event cannot be used because it has already triggered when you run your code – mplungjan Jun 02 '18 at 06:17
  • No console errors, if I do a console.log(event) with your code, it doesn`t trigger nor output anything within the console... I need to get the element clicked upon (target), and all it`s parents within the iframe... – Luc Laverdure Jun 02 '18 at 06:25

1 Answers1

2

Here should be enough tools to do what you want

Also the load event cannot be used unless you set the src later, because it has already triggered when you run your code

The fiddle works: https://jsfiddle.net/mplungjan/kqeqzusf/

SO have more stringent sandbox issues but also look at SecurityError: Blocked a frame with origin from accessing a cross-origin frame

$(function() {
  $(".iframe").each(function(i) {
    var doc = $(this)[0].contentWindow.document;
    var $body = $('body',doc);
    $body.html(`<div id="test${i}">Click me ${i}</div>`); // or set the source
    $body.on("click",function(e) { // assign a handler
      console.log(e.target.id);
    });
  });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="container">
  <iframe id="iframe1" class="iframe"></iframe>
  <iframe id="iframe2" class="iframe"></iframe>
</div>

More:

mplungjan
  • 134,906
  • 25
  • 152
  • 209