Apply “onclick” to all elements in an iFrame

前端 未结 2 1289
北恋
北恋 2021-01-17 08:07

How do I use the JavaScript DOM to apply onclick events to links inside of an iframe?

Here\'s what I\'m trying that isn\'t working:

相关标签:
2条回答
  • 2021-01-17 08:15

    It is possible for an iFrame to source content from another website on a different domain.

    Being able to access content on other domains would represent a security vulnerability to the user and so it is not possible to do this via Javascript.

    For this reason, you can not attach events in your page to content within an iFrame.

    0 讨论(0)
  • 2021-01-17 08:35

    getElementsByTagName returns a NodeCollection, so you have to iterate throgh this collection and add onclick handler to every node in that collection. The code below should work.

    var links = document.getElementById('myIframe').contentDocument.getElementsByTagName('a');
    for(var i=0;i<links.length;++i)links[i].onclick=function(){}
    

    also make sure, you run this code after the frames' content is loaded

    embed_results.onload=function(){
       // your code
    }
    
    0 讨论(0)
提交回复
热议问题