Search code examples
javascriptiframehref

Call a JS function on any link click inside an iframe


Scenario:

An iframe is loading a page with many different hyperlinks.

<iframe id=output>
    <a href="somedomain1.com"> click here </a>
    <a href="somedomain2.com"> click here </a>
    <a href="somedomain3.com"> click here </a>
</iframe>

I am aware that I cannot append onclick="jsfunction()" on a hyperlink inside an iframe.

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

Edit: Fiddle Link


Solution

  • 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] : e.target;
    
        while (el && 'A' !== el.nodeName) el = el.parentNode;
        if (!el || 'A' !== el.nodeName) return;
    
        console.log('click a tag inside iframe')
    });
    

    https://jsfiddle.net/17o093ov/2/

    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.