我有一个来自多个来源的新闻文章集合,我试图显示。有些网站不允许他们的内容在iframe
内加载,所以我想检查内容是否正在加载和重定向到原始文章,如果被阻止。
当我尝试用DOM找到iframe
时,它是未定义的,当我尝试用useRef
做同样的事情时。是否有某种方法可以检查连接是否成功,或者仅检查iframe
中的url
?
代码如下:
export default function Article(){
// just getting the source url for the iframe
const url = window.location.href.split("=")[1]
const [ article, setArticle ] = useState();
useEffect(() => {
Axios.get("http://localhost:8000/article?id=" + url).then(
(response) =>{
setArticle(response.data.link);
}
)
}, []);
// just getting the source url for the iframe
return(
<div>
<iframe id="frame" src={article}></iframe>
</div>
);
}
可以使用iframe的onload
事件。
export default function Article() {
// just getting the source url for the iframe
const url = window.location.href.split("=")[1];
const [article, setArticle] = useState();
useEffect(() => {
Axios.get("http://localhost:8000/article?id=" + url).then((response) => {
setArticle(response.data.link);
});
}, []);
handleIfrmeLoad = () => console.log("iframe loaded");
return (
<div>
<iframe id="frame" src={article} onload={handleIfrmeLoad}></iframe>
</div>
);
}