【发布时间】:2020-10-12 18:02:06
【问题描述】:
我有一个包含 iframe 的组件,我想在 react 中访问它的内容,我使用 ref 来处理 iframe,如何从 iframe 中获取所有锚点标签
这是我的代码:
const GridGenerator = () => {
const [loading, setLoading] = useState(true);
const gridIframe = useRef(null);
function handleIframe() {
setLoading(false);
const iframeItem = gridIframe.current;
const anchors = iframeItem.contentWindow.getElementsByTagName("a");
}
return (
<div>
{loading ? <div className={styles.loader} /> : null}
<iframe
title="Grid Generator"
ref={gridIframe}
src="https://collectearth.users.earthengine.app/view/collect-earth-grid-generator"
width="100%"
height="1000px"
frameBorder={0}
onLoad={handleIframe}
/>
<Link to={routes.HOME}>Go Back</Link>
</div>
);
};
所以,它运行良好,直到:
const iframeItem = gridIframe.current;
它会返回 iframe 标记,但是这条线不能正常工作
const anchors = iframeItem.contentWindow.getElementsByTagName("a");
任何解决方案?谢谢
【问题讨论】:
-
控制台有错误吗?您可能没有访问 iframe 的 DOM 的权限。
-
我得到了这个:react-dom.development.js:328 Uncaught DOMException: Blocked a frame with origin "file://" from access a cross-origin frame.
-
我就是这么想的。除非您也拥有 iframe 的网站,否则您无权访问其他域中 iframe 的 DOM。