Home  >  Q&A  >  body text

Why doesn't my iframe load in this snippet?

So I have a small piece of code here to detect whether it is a mobile browser or a desktop browser. This function works, but I tried serving different iframes depending on the browser, but the iframe didn't load. Please help fix it!

<html>
<body>
    <script>
        /* 将用户设备信息存储在一个变量中 */
        let details = navigator.userAgent;
  
        /* 创建一个包含一些移动设备关键词的正则表达式,
        用于在details字符串中搜索 */
        let regexp = /android|iphone|kindle|ipad/i;
  
        /* 使用test()方法在details中搜索regexp,
        它返回一个布尔值 */
        let isMobileDevice = regexp.test(details);
  
        if (isMobileDevice) {
            document.write("您正在使用移动设备");
        } else {
<iframe target="_parent" src="https://google.com/" style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>
        }
    </script>
</body>
</html>

I tried a PHP version with no success. please help!

P粉514458863P粉514458863421 days ago634

reply all(1)I'll reply

  • P粉785905797

    P粉7859057972023-09-16 10:20:07

    If the device detects that the user agent is a mobile device, an incompatible device message will be displayed, otherwise the browser activity will continue, even if they have desktop mode enabled in the mobile browser, the incompatible device message will still be displayed information

    <html>
    <head>
    <style type="text/css">
        body {
            margin: 0 auto;
            padding: 0;
        }
    
        #root {
            display: grid;
            justify-content: center;
            align-items: center;
            width: 100vw;
            height: 100vh;
        }
    
        #browser {
            border: 0;
            width: inherit;
            height: inherit;
        }
    </style>
    </head>
    <body>
    <div id="root"></div>
    <script type="text/javascript">
        let device = navigator.userAgent;
        let isMobile = device.includes("Android") || device.includes("iPhone") || device.includes("iPad");
        let root = document.querySelector("#root");
    
        let message = () => {
            let p = document.createElement("p");
            p.textContent = "您正在使用移动设备。";
            root.appendChild(p);
        };
    
        let browser = () => {
            let browser = document.createElement("iframe");
            browser.id = "browser";
            browser.target = "_parent";
            browser.src = "https://bing.com";
            browser.crossOrigin = "anonymous";
            root.appendChild(browser);
        }
    
        if (isMobile) {
            message();
        } else {
            browser();
        }
    </script>
    </body>
    </html>

    And you can use the ternary operator instead of the IF ELSE statement.

    isMobile ? message() : browser();

    reply
    0
  • Cancelreply