简体   繁体   中英

Javascript: Call top-level window function from inside object

I have the following webpage:

 <!DOCTYPE html> <html> <head> <meta charset='UTF-8'> </head> <body> <script>window.bark = function() { console.log('woof') } </script> <object role='img' data='https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/android.svg' onclick='window.bark()' /> </body> </html> 

I know that the content inside the object tag has its own document context, but am wondering: is there any way to permit the object to call the function bound to the window?

This would be impossible under your current implementation, and not because the object 's window is under a different global context. (In fact, that click event isn't even inside the object 's document. It's inside the top document, so scope wouldn't be a problem.)

It's because you can't effectively listen to clicks directly on an object element. The same would apply to an iframe , for example. Click events are triggered inside the element's document, not on the element itself.

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