我对 iOS 编程的整个 Web 方面完全陌生,所以请耐心等待:P。我的目标是从网站上获取一个 JavaScript 文件,然后“注入”该脚本,以便我可以使用它登录另一个网站。我不确定我的做法是否是“最好的”,所以如果你发现它们有不好的地方,请告诉我!:D
因此,在我的应用程序中,我们从一个视图开始,其中用户有两个文本框和一个提交按钮。一个用于用户名的文本框,一个用于密码的文本框。当用户点击提交时,我想加载页面,将输入的用户名和密码放在 HTML 页面上的正确位置!
- (IBAction)signInTouched:(id)sender {
if (userName.text.length > 0 && pass.text.length > 0)
{
NSString *theSite = @"www.thesite.com";
NSURL *theURL = [NSURL URLWithString:theSite];
NSURLRequest *loginRequest = [[NSURLRequest alloc] initWithURL:theURL];
[webView loadRequest:loginRequest]; // Webview is the web view :P
NSURL *jsSite = [NSURL URLWithString:@"www.ThePlaceWithTheJS"];
NSString *jsString = [NSString stringWithContentsOfURL:jsSite encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:jsString];
NSString *userValue = userName.text;
NSString *passValue = pass.text;
NSString *javaFunction = [NSString stringWithFormat:@"login(%@,%@)", userValue, passValue]; // login is the function in the javascript
[webView stringByEvaluatingJavaScriptFromString:javaFunction];
}
}
然后,这里是 JS 文件:
<script type='text/javascript'>
function login(username,password){
var usernameBox = document.getElementById("ctl00_plnMain_txtLogin");
usernameBox.value = usernameBox.value + username;
var passwordBox = document.getElementById("ctl00_plnMain_txtPassword");
passwordBox.value = passwordBox.value + password;
}
</script>
所以,问题是我不知道我是否做得很好,或者如何让它正常工作。每当我测试它时,文本都不会加载到网站上的字段中。所以它显然在某个地方出错了......但是在哪里?