将javascript放入uiwebview问题
我正在尝试在 webViewDidFinishLoading 中运行以下代码:
NSString* len = [self.webView stringByEvaluatingJavaScriptFromString:@"document.links.length"];
NSInteger lenVal = [len intValue];
for( int i=0; i<lenVal; ++i ) {
NSString *value = [[NSNumber numberWithInt: i] stringValue];
NSString *link = @"document.links[";
link = [link stringByAppendingString:value];
link = [link stringByAppendingString:@"]"];
NSString* links = [self.webView stringByEvaluatingJavaScriptFromString:link ];
NSLog(@"val: %@", links);
}
这个想法是我有一个已加载的 webview,我所在的页面我想要然后获取页面上显示的所有链接。在 chrome 中打开控制台,输入 document.links 给出 83(链接数量)和 document.links[0],尽管 [82] 显示我想要的内容。但是当我运行这段代码(以及一堆其他尝试)时,我似乎无法获得具有任何值的链接(似乎总是返回空)。
有人可以帮忙吗?
I'm trying to run the following code in my webViewDidFinishLoading:
NSString* len = [self.webView stringByEvaluatingJavaScriptFromString:@"document.links.length"];
NSInteger lenVal = [len intValue];
for( int i=0; i<lenVal; ++i ) {
NSString *value = [[NSNumber numberWithInt: i] stringValue];
NSString *link = @"document.links[";
link = [link stringByAppendingString:value];
link = [link stringByAppendingString:@"]"];
NSString* links = [self.webView stringByEvaluatingJavaScriptFromString:link ];
NSLog(@"val: %@", links);
}
The idea is that I have a webview that is loaded, the page I am on I want to then get all the links displayed on the page. Opening a console in chrome an typing document.links gives 83 (# of links) and document.links[0] though [82] display just what I want. But when I run this code (and a bunch of other attempts), I can't seem to get links to have any value (always seems to return empty).
Can anyone please help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的方向是正确的,但如果不先将 JavaScript 对象转换为字符串(通常使用
.toString()
为),则无法使用
(尽管后者不适用于 DOM 对象)。stringByEvaluatingJavaScriptFromString
返回 JavaScript 对象>JSON.stringify(..)尝试将第 8 行更改为
看看会发生什么。
You're on the right track, but you can't return a JavaScript object with
stringByEvaluatingJavaScriptFromString
without first converting it to a string, typically with.toString()
ofJSON.stringify(..)
(although the latter won't work for DOM objects).Try changing line 8 to
and see what happens.