如何用JavaScript获取当前页面所在的iframe?
如何判断当前页面所在的iframe
针对你的场景,有两种常用实现方式,根据页面是否同域选择即可:
方法一:同域场景下直接获取iframe元素
如果Page A和Page B属于同一域名,在Page B中可以通过window.frameElement直接拿到承载当前页面的iframe DOM节点,进而获取它的ID或其他标识:
/* Page B: */ // 获取当前页面所在的iframe元素 const hostIframe = window.frameElement; if (hostIframe) { const iframeId = hostIframe.id; console.log(`当前页面运行在 iframe: ${iframeId}`); // 根据不同iframe执行对应逻辑 switch(iframeId) { case 'frameA': // frameA专属逻辑 break; case 'frameB': // frameB专属逻辑 break; default: // 其他iframe的情况 } } else { console.log('当前页面未在iframe中运行'); }
方法二:跨域场景下通过URL参数传递标识
如果Page A和Page B存在跨域限制,浏览器同源策略会阻止window.frameElement的访问,这时候可以在Page A加载iframe时,给目标URL添加标识参数:
修改Page A的代码:
/* Page A: */ if (openinA) $("#frameA").attr("src", "pageb.php?from=frameA"); else $("#frameB").attr("src", "pageb.php?from=frameB");
Page B中解析参数:
/* Page B: */ // 解析URL中的查询参数 const urlParams = new URLSearchParams(window.location.search); const fromIframe = urlParams.get('from'); console.log(`当前页面运行在 iframe: ${fromIframe}`); // 后续根据fromIframe的值执行对应逻辑
内容的提问来源于stack exchange,提问作者eluc
相关产品推荐
相关产品推荐

