gpt4 book ai didi

Javascript:检测何时添加 iframe 且 src 不可检索

转载 作者:搜寻专家 更新时间:2023-11-01 04:21:23 26 4
gpt4 key购买 nike

给定的第 3 方脚本在特定条件下将 iframe 添加到 DOM。如果 iframe 正确加载,则一切都已完成。但是,有时,该 iframe 的 src 会导致 404、网络超时或其他错误。第 3 方脚本无法妥善处理此问题。

我想在我的脚本中对此进行监控,并且每当 iframe 无法加载时触发我的脚本。有什么办法吗?它看起来像这样:

function callWhenElementFails(element) {
if (element is_a iframe)
invoke_my_handler;
else
do nothing
}

一个更简单的问题:给定一个 iframe 元素,我如何检查它是否加载或加载失败?我可以在“网络”选项卡下的“开发人员工具”中看到 src 失败;我如何以编程方式查询它。

请注意,我的代码不是加载iframe的代码,第三方代码很难修改和添加。

Detecting if iframe src is displayable解决了类似的问题,但没有成功。

突变观察器可能是一种方法,但我希望更简单的方法会更好。

最佳答案

function badIframe(iframe) {
return new Promise(resolve => {
// This uses the new Fetch API to see what happens when the src of the iframe is fetched from the webpage.
// This approach would also work with XHR. It would not be as nice to write, but may be preferred for compatibility reasons.
fetch(iframe.src)
.then(res => {
// the res object represents the response from the server

// res.ok is true if the repose has an "okay status" (200-299)
if (res.ok) {
resolve(false);
} else {
resolve(true);
}

/* Note: it's probably possible for an iframe source to be given a 300s
status which means it'll redirect to a new page, and this may load
property. In this case the script does not work. However, following the
redirects until an eventual ok status or error is reached would be much
more involved than the solution provided here. */
})
.catch(()=> resolve(true));
});
}

new MutationObserver(async records => {
// This callback gets called when any nodes are added/removed from document.body.
// The {childList: true, subtree: true} options are what configures it to be this way.

// This loops through what is passed into the callback and finds any iframes that were added.
for (let record of records) {
for (let node of record.addedNodes) {
if (node.tagName === `IFRAME` && await badIframe(node)) {
// invoke your handler
}
}
}
}).observe(document.body, {childList: true, subtree: true});

关于Javascript:检测何时添加 iframe 且 src 不可检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57940799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com