JQuery.on ('load') does not work with the / iframe object, whereas .addEventListener ('load')

I am trying to modify the contents of an iframe / object by adding a script to it. At the moment, I have something like this:

// "script" is a node with an self-called function as its content
$(function() {
    $('object, iframe').each(function() {
        this.addEventListener('load', function() {
            this.contentDocument.getElementsByTagName('head')[0].appendChild(script.cloneNode(true));
        });
    });
});

And it works as expected (the script does its job, and it is added to the DOM iframe), but the problem occurs when I try to do it in the "jQuery" way:

// "script" is a node with an self-called function as its content
$(function() {
    $('object, iframe').each(function() {
        $(this).on('load', function() {
            this.contentDocument.getElementsByTagName('head')[0].appendChild(script.cloneNode(true));
        });
    });
});

In the previous code, the script will not be added to the dom iframe.

Is there a reason why the version is .on('load')not working? What could be wrong? Did I miss something?

PS: iframe has the same origin.

+4
source share
1 answer

this , . :

$(function() {
    $('object, iframe').each(function () {
        $(this).on('load', function (event) {
            event.target.contentDocument.getElementsByTagName('head')[0].appendChild(script.cloneNode(true));
        });
    });
});

Cf. https://api.jquery.com/event.target/

-1

Source: https://habr.com/ru/post/1681823/


All Articles