javascript - 无法使用 Javascript 和 WebView 单击 HTML 输入按钮(可能是 iframe 问题,不确定)

标签 javascript web-scraping wkwebview userscripts

我正在开发一个 iOS 应用程序,该应用程序使用注入(inject)的 javascript 在 webview 中执行一些操作。我正在尝试按下路由器网络界面上的提交按钮(所以我不能给你一个 url)。我在网上尝试了许多其他建议的解决方案,但没有任何效果。我必须做的一件事是单击 type=SUBMIT 的输入按钮,但无论出于何种原因它都没有响应。我尝试使用 .click() 并调用 onClick 事件处理程序,但没有任何效果。任何帮助表示赞赏。 HTML 代码如下:

<div class="fix_button">
  <table width="100%" border="0" cellpadding="0" cellspacing="2">
    <tbody>
      <tr>
        <td nowrap="" colspan="2" align="center">
          <input class="cancel_bt" type="RESET" name="Cancel" value="Cancel" onclick="doCancel();" languagecode="51">
          &nbsp;
          <input class="apply_bt" type="SUBMIT" name="Apply" value="Apply" onclick="return checkData();" languagecode="50">
        </td>
      </tr>
    </tbody>
  </table>
</div>

输入按钮是带有class="apply_bt" 的按钮。此 div 位于 iframe 内,并提交位于此框架内另一个 iframe 内的数据。结构有点像这样:

<iframe>
    // Contains the Apply Button
    <div class="fix_button"></div>

    // Contains the iframe where the info to be submitted is
    <div id="main" class="main_top_button">
        // Contains data to be submitted
        <iframe src="WLG_2g_wireless2.htm&amp;todo=wifi_primary_init" id="2g_setting" name="wl2gsetting" onload="SetCwinHeight(this.id)" marginheight="0" marginwidth="0" scrolling="no" width="100%" frameborder="0" height="288px">
        </iframe>
    </div>
</iframe>

这是我用来点击按钮的代码:

// Gets the outer iframe
iframe1 = document.getElementById("formframe");
// Gets the html within the iframe
var innerDoc=iframe1.contentDocument || iframe1.contentWindow.document;
// Gets iframe within the iframe
innerframe = innerDoc.getElementById("2g_setting");
// Gets the html within the inner iframe
var innerDoc2=innerframe.contentDocument || innerframe.contentWindow.document;

// I Enter some data in the inner iframe (not shown), this portion 
// of the code works perfectly. I can see fields being entered and 
// buttons being clicked.
// Then I click the apply button...
innerDoc.getElementsByName("Apply")[0].click()
// And nothing happens

我能够获取元素并从应用按钮读取数据,例如它的文本,但我无法对按钮执行 .click() 操作。另外,我没有收到任何错误。我不知道为什么它不起作用。请帮忙!

最佳答案

click方法仅对 <a> 可靠标签。您应该改为触发合成事件。这也将保证调用任何事件处理程序,无论它们是否设置为 html 属性,element.onclick 、addEventListener 或您可能正在使用的任何库。

参见 How can I trigger a JavaScript event click

使用上述问题的代码,执行以下操作。

var button = innerDoc.getElementsByName("Apply")[0] ;

fireEvent(button, 'click')

关于javascript - 无法使用 Javascript 和 WebView 单击 HTML 输入按钮(可能是 iframe 问题,不确定),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339297/

相关文章:

javascript - NextJS - 在页面组件加载时加载外部脚本

python - 确定网站是否是网上商店

javascript - 抓取 html 页面结果..顺序不正确

ios - 向 WKWebView 添加加载栏并选择其颜色

html - HTML输入自动完成功能在WKWebview中不起作用

javascript - 使用纯 JavaScript 从前 5 个标签中获取 “id” 并在输出中用逗号分隔它们

javascript - 使用 jQuery formwizard 重新加入分支?

ios - 向 WKWebView 发送消息抛出错误

javascript - 从 JavaScript OS.File.DirectoryIterator 返回数组

python - 访问没有标签的html元素