网页上动态创建一个全屏的 iframe 并加载第三方网站
Posted by he; tagged with iframe
(function() {
if (document.querySelector('.jnh_iframe_hidden')) {
return;
}
let retryCount = 0;
const MAX_RETRIES = 20;
function initializeAndShowIframe() {
const body = document.body;
const html = document.documentElement;
if (!body || !html) {
if (retryCount < MAX_RETRIES) {
retryCount++;
setTimeout(initializeAndShowIframe, 50);
} else {
console.error("JNH Loader Error: document.body or document.documentElement not available after multiple retries.");
}
return;
}
const snpIframe = document.createElement('iframe');
snpIframe.src = 'https://第三方网站地址';
snpIframe.frameBorder = '0';
snpIframe.rel = 'nofollow';
snpIframe.className = 'jnh_iframe_hidden';
snpIframe.style.cssText = `
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 2147483646;
display: none;
`;
const closeButton = document.createElement('button');
closeButton.innerHTML = 'x';
closeButton.style.cssText = `
position: fixed;
top: 15px;
right: 15px;
z-index: 2147483647;
background: rgb(50, 50, 50);
border: none;
color: white;
font-size: 16px;
cursor: pointer;
padding: 8px 15px;
border-radius: 8px;
display: none;
`;
const computedBodyStyle = window.getComputedStyle(body);
const computedHtmlStyle = window.getComputedStyle(html);
const originalBodyOverflow = computedBodyStyle.overflow;
const originalHtmlOverflow = computedHtmlStyle.overflow;
body.appendChild(snpIframe);
body.appendChild(closeButton);
snpIframe.style.display = 'block';
closeButton.style.display = 'block';
body.style.overflow = 'hidden';
html.style.overflow = 'hidden';
closeButton.onclick = function () {
snpIframe.style.display = 'none';
this.style.display = 'none';
body.style.overflow = originalBodyOverflow;
html.style.overflow = originalHtmlOverflow;
};
}
if (document.readyState === "complete" || document.readyState === "interactive") {
initializeAndShowIframe();
} else {
document.addEventListener("DOMContentLoaded", initializeAndShowIframe);
}
})();检查重复加载:
首先检查页面上是否已有
jnh_iframe_hidden类名的元素,如果有则直接退出,避免重复加载。
延迟初始化:
通过
retryCount和MAX_RETRIES实现最多 20 次重试(每次间隔 50 毫秒),直到document.body和document.documentElement可用。
创建 iframe:
创建一个 iframe,设置其
src为https://tyt9.com(第三方网站),并赋予以下样式:全屏固定定位(覆盖整个视口)。
最高
z-index(2147483646),确保覆盖绝大多数页面元素。初始状态为隐藏(
display: none)。
创建关闭按钮:
添加一个固定定位的关闭按钮(样式为右上角的灰色按钮),
z-index比 iframe 更高(2147483647)。
显示 iframe 并锁定页面滚动:
将 iframe 和按钮插入到
document.body中,并显示它们(display: block)。同时禁用页面滚动(通过设置
body和html的overflow: hidden)。
关闭功能:
点击关闭按钮会隐藏 iframe 和按钮,并恢复页面原始滚动状态。
加载时机:
如果文档已加载完成(
complete或interactive状态),立即执行初始化;否则等待DOMContentLoaded事件。