定位iframe的表单正在Chrome中打开新标签页

时间:2017-04-22 12:35:23

标签: javascript html google-chrome iframe

我正在尝试将表单提交到iframe,这两个表单都是使用javascript在我的项目中动态构建的。

<script>
document.querySelector('iframe').setAttribute('id', iframeId);
document.getElementById(iframeId).setAttribute('name', target);
document.getElementById(iframeId).setAttribute('width', width);
document.getElementById(iframeId).setAttribute('height', height);

document.querySelector('form').setAttribute('id', id);
document.getElementById(id).setAttribute('target', target);
document.getElementById(id).setAttribute('action', actionURL);

document.getElementById(id).submit();
<script>

稍后在浏览器Web Inspector中查看它的方式。

<iframe id="my_frame" name="my_frame" width="700" height="400">
        <p>Your browser does not support iframes.</p>
</iframe>

<form id="my_form" target="my_frame" action="http://localhost:8080/MyProject/loadService" method="POST" style="display: none;">
    <input type="hidden" name="userId"/>
    <input type="hidden" name="locale"/>
</form>

这适用于我在Firefox中,但在Chrome中它会打开一个新标签。我尝试了here给出的解决方案,但它没有解决问题。任何人都可以建议缺少什么?

3 个答案:

答案 0 :(得分:2)

我有同样的问题。我跟着this帖子找了解它。尝试动态生成iframe,并确保在将iframe附加到DOM之前设置表单将要定位的名称/ ID。

示例:

iframe = document.createElement('iframe');
iframe.name = 'target_name';
iframe.id = 'target_name';

// now append to DOM, ideally to a container element
document.body.appendChild(iframe);

答案 1 :(得分:2)

从你的html中删除iframe并尝试这样做:

//Create the iframe, set its attributes and append it before the form
var iframe = document.createElement('iframe');
iframe.name = 'my_frame';
iframe.id = 'my_frame';
iframe.width = '400';
iframe.height = '700';
var form_element = document.getElementById('my_form');
form_element.parentNode.insertBefore(iframe, form_element);

//Submit form to iframe
document.getElementById('my_form').submit();

答案 2 :(得分:0)

This post建议在提交表单之前动态添加表单的target-attribute。

由于您是动态创建表单和iframe,您是否尝试在表单之前创建iframe并将其添加到DOM? 也许target-id必须存在于表单创建时才能正常工作。