javascript - 预填充 WebView 文本字段

标签 javascript ios objective-c uiwebview

我需要在 UIWebView 中预填充文本字段,我了解到 javascript 是解决此问题的最佳方式。不幸的是,我对 javascript 一无所知,并且在过去的几个小时里一直在摸索,一无所获。

最近的拙劣尝试:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // username field id = username_5 & pw field id = password_5
    NSString *javascript = @"\
    var user = 'testUser';\
    var pw = 'testPW';\
    document.getElementById('username_5').value = user; \
    document.getElementById('password_5').value = pw; \
    ;";
    // Execute JS
    [_emailWebView stringByEvaluatingJavaScriptFromString:javascript];
}

谁能指出我正确的方向?

-编辑-

我也尝试过延迟调用,以防页面未完全加载并且我调用类似:

- (void)webViewDidFinishLoad:(UIWebView *)wv
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self performSelector:@selector(injectJavascript) withObject:nil afterDelay:1.0];
}

- (void)injectJavascript
{
    [self.emailWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('password_5').value = 'testPW';"]];
    [self.emailWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.alert('test');"]];
}

出现警告,但 ID 为 password_5 的字段未填写。

相关字段嵌套在表单中。不知道这有什么不同吗?

-编辑 2-

我很确定问题与目标网站上的 HTML/嵌套有关,因为我刚刚在另一个网站上尝试过并且有效。

目标网站是这样嵌套的:

<html>
  <head> … </head>
    <body onload="FinishLoad(1);hideJSWarn();">
      <div id="noJSWarn" class="cssSecurityWarning" style="display: none;"> … </div>
      <table id="table_LoginPage_1" > … </table>
      <table id="table_LoginPage_2" > … </table>
      <blockquote>
        <form id="frmLogin_4" onsubmit="return Login(1)" autocomplete="off" method="POST" action="login.cgi" name="frmLogin">
          <input id="tz_offset_5" type="hidden" name="tz_offset"></input>
          <table id="table_LoginPage_3" >
            <tbody>
              <tr> … 
                <td valign="top">
                  <table id="table_LoginPage_6" >
                    <tbody>
                      <tr>
                        <td> … </td>
                        <td> 
                          <input id="username_5" type="text" size="20" name="username"></input>

最佳答案

您必须将 javascript 代码放在一个 NSString 中,然后使用 stringByEvaluatingJavaScriptFromString 执行。这是代码的样子:

 [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('email').value = '%@'", email]];
 [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('pass').value = '%@'", password]];

关于javascript - 预填充 WebView 文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18145807/

相关文章:

ios - 您将如何检查用户是否处于事件状态并将其推送到 Parse?

javascript - java加密aes值和javascript加密值不匹配

javascript - 如何用 jQuery 仅替换该元素的文本?

javascript - 密码恢复链接上不会加载任何内容

ios - 找不到 SpriteBuilder 图像文件

iphone - 从 iOS 应用访问 iOS 崩溃报告

ios - 如何在 Objective-C 宏中编写多条指令?

javascript - 如何在第二次点击后销毁cookie

ios - iPad 上未显示应用程序图标

ios - TabBar 图像的大小应该是多少?