Javascript window.matchMedia在iframe中不工作

Javascript window.matchMedia在iframe中不工作,javascript,html,matchmedia,Javascript,Html,Matchmedia,我正在使用window.matchMedia检测设备方向。以下代码按预期工作-每个方向更改都以正确的值记录到控制台: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, ini

我正在使用
window.matchMedia
检测设备方向。以下代码按预期工作-每个方向更改都以正确的值记录到控制台:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Test App</title>
  </head>
  <body>
    <script type="application/javascript">
        let isIframe= () => {
            try {
                return window.self !== window.top;
            } catch (e) {
                return true;
            }
        }    

         let onOrientationChange = () => {
            const isLandscape = window.matchMedia("(orientation: landscape)").matches;
            console.log("Event: " + (isIframe() ? "Iframe " : "") + "landscape:" + isLandscape);
        }

        let mediaQueryList = window.matchMedia("(orientation: landscape)");
        
        console.log("Onload: " + (isIframe() ? "Iframe " : "") + "landscape:" + mediaQueryList.matches);

        mediaQueryList.addListener(onOrientationChange);
    </script>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root">Hello World in Iframe</div>
  </body>
</html>
我使用的是
addListener
而不是
addEventListener
,因为第二个函数在所有Safari版本上都不起作用

在Safari 14以及Chrome和Firefox的开发工具上测试

我的问题是-为什么在
iframe
中不调用
addListener
回调


谢谢。

如果iframe由于具有固定的宽度和高度而无法更改其大小,则无法在其内部触发与调整大小相关的事件,包括与
方向有关的事件

你可以做两件事来让它工作;您可以将iFrame的宽度和高度设置为
100%
,也可以让媒体查询检测代码位于主窗口内,并在触发更改事件时使用传递方向状态

1) 将iFrame大小更改为
100%
,以便在触发横向/纵向事件时调整其大小 在主页中,将主体设置为全高,将iframe设置为全宽/高(使用CSS)

正文{
高度:100vh;
保证金:0;
}
iframe{
宽度:100%;
身高:100%;
}
您可以测试的实时示例:

2) 在主页上进行媒体查询检测,并在定向事件触发时使用
postMessage
向iFrame发送消息
index.html

让iframe=document.querySelector('iframe');
让onOrientationChange=()=>{
iframe.contentWindow.postMessage({
isLandscape:window.matchMedia(“(方向:横向)”).matches
}, '*');
}
iframe.addEventListener('load',onOrientationChange);
const mediaQueryList=window.matchMedia(“(方向:横向)”);
addListener(onOrientationChange);
iframe.html

window.addEventListener(“消息”,“事件)=>{
if(event.data.isLandscape){
console.log('iFrame-scape');
}否则{
console.log(“iFrame肖像”);
}
});
您可以测试的实时示例:

 <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root">Hello World</div>
    <iframe id="game" src="iframeContent.html" frameborder="0" style="width: 960px; height: 600px;"></iframe>
  </body>