Cocoa:发出url数据请求,运行本地DOM改变javascript,存储修改后的html

时间:2012-11-22 23:23:59

标签: objective-c xcode cocoa nsurlconnection

假设我有一些来自网页的数据:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:myurl]];
[request setHTTPMethod:@"GET"];
NSData* returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString* html = [[NSString alloc] initWithData:returnedData encoding:NSUTF8StringEncoding];

我还有一个本地javascript脚本,可以对数据运行一些查询并修改DOM。目前,为了实现这一目标,我正在使用上面收到的HTML,创建一个webview并将其加载到其中:

[NSString stringWithFormat:@"<script>%@</script>%@", myscript, html];

然后,我在webview上的didFinishLoadForFrame事件,调用

NSString* modifiedhtml = [sender stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"]]

这给我留下了我的modifiedhtml,我可以随意做。然而,这似乎并不优雅,特别是因为只允许在主线程上创建webview,并且整个过程最好在后台线程中运行,同样,脚本偶尔会抛出错误并且webview加载事件不是所以我有越来越多的专门用于处理此事件的超时。总而言之,这是一个很难看的混乱。

在一个理想的世界里,我会在第一次通过时应用这个javascript,而根本不创建webview。我一直在尝试各种各样的事情:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:myurl]];
[request setHTTPMethod:@"GET"];
NSData* returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString* html = [[NSString alloc] initWithData:returnedData encoding:NSUTF8StringEncoding];
NSString* modifiedhtml = [request stringByEvaluatingJavaScriptFromString: myscript]];

脚本设置为返回页面但无效。

有没有关于如何更优雅,更有效地处理这个问题的建议?

1 个答案:

答案 0 :(得分:-1)

为避免使用网页视图并假设您的html标记为head,您可以执行以下操作:

NSArray *tempArray = [html componentsSeparatedByString:@"<head>"];
NSString *modifiedHtml = [NSString stringWithFormat:@"%@<head>%@%@", [tempArray objectAtIndex:0], yourScriptString, [tempArray objectAtIndex:1]];

它会将您的脚本插入现有的head标记中。您应该通过通常的健全性检查来完成代码。