下面react组件
import React from "react";
const App = (props) => {
const iframe = React.useRef();
React.useEffect(() => {
(async () => {
// await new Promise((r) => setTimeout(r, 1));
iframe.current.contentDocument.body.style.backgroundColor = "salmon";
})();
}, []);
return (
<>
<iframe ref={iframe} title="foo" />
</>
);
};
export default App;
在chrome里iframe有颜色,但是Firefox里就没有。
如果把 await new Promise((r) => setTimeout(r, 1000)); 这行注释拿掉,也就是加一点sleep, Firefox也有颜色了。为什么?
分别在chrome和Firefox里打开 https://codesandbox.io/s/determined-pike-jc5h3?file=/src/App.js 就能看到现象了。
如果在本地PC上执行,在Firefox下,刷新页面是会感觉到有一瞬间iframe有颜色,然后颜色消失了。