Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在iframe中的任何链接上调用JS函数_Javascript_Iframe_Href - Fatal编程技术网

Javascript 在iframe中的任何链接上调用JS函数

Javascript 在iframe中的任何链接上调用JS函数,javascript,iframe,href,Javascript,Iframe,Href,情景: iframe正在加载包含许多不同超链接的页面 <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> 我知

情景:

iframe正在加载包含许多不同超链接的页面

<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>

我知道我不能在iframe内的超链接上追加
onclick=“jsfunction()”

但是有没有办法在iframe中的任何链接点击上调用JS函数呢

编辑: 您可以这样做:

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')
});

请注意,只有当iframe与父页面具有相同的来源时,这才有效。否则,出于安全考虑,浏览器将阻止访问
contentDocument

您可以执行以下操作:

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')
});


请注意,只有当iframe与父页面具有相同的来源时,这才有效。否则,出于安全考虑,浏览器将阻止访问
contentDocument

您可以共享html代码吗?发布完整代码,或将其发布在Fiddle上?您可以共享html代码吗?发布完整代码,或将其发布在Fiddle上。但是如何只捕获超链接的点击?我的意思是只有标签点击我更新了我的答案,包括检查
a
标签点击。但是对于一些
a
标记,它将不起作用,因为页面在这些标记上已经有了事件处理程序,阻止了我的代码工作。您可以尝试单击
登录
链接(谢谢:)即可。但是如何只捕获超链接的点击?我的意思是只有标签点击我更新了我的答案,包括检查
a
标签点击。但是对于一些
a
标记,它将不起作用,因为页面在这些标记上已经有了事件处理程序,阻止了我的代码工作。您可以尝试单击
登录
链接(谢谢:)