Javascript 在iframe中的任何链接上调用JS函数
情景: iframe正在加载包含许多不同超链接的页面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 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
标记,它将不起作用,因为页面在这些标记上已经有了事件处理程序,阻止了我的代码工作。您可以尝试单击登录链接(谢谢:)