简体   繁体   中英

Fire JavaScript event with custom parameter and catch it with jQuery

I'm currently firing a custom JavaScript event like that from the page itself to the iframe document:

// Create iframe
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'URL to load');
document.body.appendChild(iframe);

// Event itself
var event = document.createEvent('HTMLEvents');
event.custom = 'example param';
event.initEvent('custom', false, true);
iframe.contentWindow.window.document.dispatchEvent(event);

Now on this iframe page I have jQuery available. How could I catch the event (which works) and also (important) get the custom (object) parameter?

Catching it like that:

$(document).on('custom', function(e, param) {
    alert(e); // [object Object] -> normal jQuery event data without any special data
    alert(e.custom); // undefined
    alert(param); // undefined
});

How could I get the custom parameter data without adding jQuery to the page itself which contains the iframe?

jQuery wraps the original DOM event. The original event should be available through the originalEvent property of the jQuery event.

e.originalEvent.custom

should evaluate to your custom value, in this case 'example param' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM