document.elementFromPoint(x,y) to get element inside iframe

前端 未结 2 549
渐次进展
渐次进展 2021-01-21 16:16

I am trying to get elements in html page, i use document.elementFromPoint(x,y) to detect input elements; it works fine when there are no iframes. But inside iframes it does not

相关标签:
2条回答
  • 2021-01-21 16:37

    As per the documentation here:

    "If the element at the specified point belongs to another document (for example, an iframe's subdocument), the element in the DOM of the document the method is called on (in the iframe case, the iframe itself) is returned."

    Meaning that it should return the iframe if your current DOM context is the iframe's parent. Also there are cross domain security issues you should read up on if the iframe is from another domain.

    If it is from your domain and you wish to get the element inside of the iframe you would do the following:

    var el = document.elementFromPoint(x, y);
    if (el instanceof HTMLIFrameElement)
        el = el.contentWindow.document.elementFromPoint(x, y);  //Not sure if you need to update x, y to account for being inside another dom.
    
    0 讨论(0)
  • 2021-01-21 16:58

    If your iframe is not on the same domain as your website, you won't be able to select tags using jquery/javascript

    0 讨论(0)
提交回复
热议问题