【问题标题】:Using javascript to select a radio button inside an iframe使用 javascript 选择 iframe 内的单选按钮
【发布时间】:2019-06-06 23:29:21
【问题描述】:

当我在test2.php 中使用document.querySelector("input[value='female']").click() 并选择值为female 的单选按钮时,它工作正常,但是当test2.php 在iframe 内时,它在test1.php 中不起作用。有什么办法可以解决这个问题吗?

test1.php

<iframe src="http://chatwithibot.com/test2.php"></iframe>

test2.php

<form action="/testx.php" method = "POST">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
<input type="submit" value="Submit">
</form> 

编辑:重复的解决方案链接似乎只回答有关如何从 iframe 中选择内容的问题,而不是如何更改它们。

【问题讨论】:

  • @JordanS 我读了那个,并尝试了 document.querySelectorAll('iframe').("input[value='female']").click();但它似乎不起作用。
  • 你可以简单地在&lt;script&gt;&lt;/script&gt;的iframe中添加radio click js代码

标签: javascript php


【解决方案1】:

让我们将id 发送给您的iframe,以确保我们可以毫无困难地找到它:

<iframe id="testpage" src="http://chatwithibot.com/test2.php"></iframe>

然后:

document.getElementById("testpage").contentWindow.document.querySelector("input[value='female']").click()

解释:

  • 我们找到iframe
  • 我们使用它的contentWindow.document
  • 从那时起,我们可以像您一样拨打querySelector

【讨论】:

  • 这一切都很完美。但是,在我真正使用它之前,还有最后一个障碍要克服。我实际上需要将它与跨源一起使用,并且我不想关闭谷歌浏览器上的跨源块,因为我听说这是一个安全漏洞。无论如何绕过这个?我在这里问了另一个问题:stackoverflow.com/questions/54157154/…
  • 您可以将您的服务器用作代理。假设您打算在 iframe 中加载页面 XYZ,您可以创建一个 XYZ.php 页面,该页面向 XYZ 发送请求并在页面中显示响应。您将需要解决可能由相对 URL 引起的问题。此外,请确保您所做的一切都是善意和合法的。
【解决方案2】:

必须访问 iframe 以在他内部选择单选按钮。下一个代码访问实际文档中的所有 iframe,并为每个 iframe 运行一个回调函数。

document.querySelectorAll('iframe').forEach( item =>
   item.contentWindow.document.body.querySelector("input[value='female']").click()
)

如果只需要访问一个 iframe 试试这个:

document.getElementById("frame_id").contentWindow.document.querySelector("input[value='female']").click()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 2015-07-20
    相关资源
    最近更新 更多