【问题标题】:JS - getElementById inside a frameJS - 框架内的 getElementById
【发布时间】:2018-02-14 11:08:40
【问题描述】:

我正在尝试在我的网页中插入一个位于外部网页中的表单。

我没有此表单的直接网址,因此我尝试以这种方式导航框架:

function showForm() {
        var newIframe = document.createElement('iframe');
        newIframe.width = '800'; newIframe.height = '400';
        newIframe.src = "websiteURL"
        document.body.appendChild(newIframe);
        window.frames["iframe"].document.getElementById('HM_Item1_4_1_1').click();
    }

但是从控制台我得到:

Uncaught TypeError: Cannot read property 'iframe' of undefined

外部网站的主页已加载,但重定向不起作用。

【问题讨论】:

    标签: javascript iframe getelementbyid


    【解决方案1】:

    您正在尝试获取 window.frames["iframe"] ......但您创建的 iframe 根本没有 nameid,更不用说匹配 "iframe"

    无论如何,在框架集合中搜索 iframe 是没有意义的。

    已经在newIframe 变量中引用了它

    只需将window.frames["iframe"] 替换为newIframe


    一旦你解决了这个问题,你的下一个问题就是document is the wrong property to access


    一旦你解决了这个问题,你的下一个问题就是你说 iframe 指向了一个不同的网站。所以你必须处理cross-origin issues

    【讨论】:

    • @Pickerroll — 这是一种冗长而臃肿的方法。只需使用newIframe
    【解决方案2】:

    请记住,您在执行此操作时可能会遇到不同的安全性和跨域错误。

    请记住在使用 onload 事件对其进行操作之前等待 iframe 内容加载:

    function showFrame() {
            const newFrame = document.createElement('iframe');
            newFrame.width = '800';
            newFrame.height = '800';
            newFrame.src = 'https://www.gorkahernandez.com';
            newFrame.onload = function() {
                const content = newFrame.contentDocument ? newFrame.contentDocument : newFrame.contentWindow.document;
                content.getElementById('HM_Item1_4_1_1').click();
    
            }
            document.body.appendChild(newFrame);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      相关资源
      最近更新 更多