Saurabh Saurabh - 1 year ago 84
Javascript Question

Call a JS function on any link click inside an iframe


An iframe is loading a page with many different hyperlinks.

<iframe id=output>
<a href=""> click here </a>
<a href=""> click here </a>
<a href=""> click here </a>

I am aware that I cannot append
on a hyperlink inside an iframe.

But is there any way to call a JS function on any link click inside an iframe?

Fiddle Link

Answer Source

You could do this:

const iframe = document.getElementById('output');
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

iframeDoc.addEventListener('click', (e) => {
    console.log('click inside iframe')
    if (e.metaKey || e.ctrlKey || e.shiftKey) return;
    if (e.defaultPrevented) return;
    // ensure link
    // use shadow dom when available
    var el = e.path ? e.path[0] :;

    while (el && 'A' !== el.nodeName) el = el.parentNode;
    if (!el || 'A' !== el.nodeName) return;

    console.log('click a tag inside iframe')

Please be aware that this only works if the iframe has the same origin as the parent page. Otherwise accessing contentDocument will be blocked by browser for security matters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download