Reputation: 34810
I am trying to imitate real user behavior on a website by loading a URL into an offscreen web view and interacting via Javascript using WebScriptObject
and its evaluateWebScript:
method. There are many images on the web page, and I don't want to load any of them as I don't need them and they consume too much bandwidth and slow down loading times. How can I let web view load everything in order to execute Javascript on the window (HTML JS and CSS files and their dependencies if any), but prevent loading any media?
Upvotes: 2
Views: 216
Reputation: 34810
After some struggling, I've found a really simple way to solve my problem. This works if image URLs are properly formatted (e.g. ending with) with their respective extensions:
-(NSURLRequest *)webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource{
BOOL isRequestImage = [self isRequestImage:request];
if(isRequestImage){
return nil; //don't bother loading images
}
...
}
Where:
-(BOOL)isRequestImage:(NSURLRequest*)request{
NSString *absoluteString = [request.URL.absoluteString lowercaseString];
if([absoluteString hasSuffix:@".png"] || [absoluteString hasSuffix:@".jpg"] || [absoluteString hasSuffix:@".jpeg"]){
return YES;
}
return NO;
}
All the images on the site I'm accessing have either jpg
or png
extension, for convenience's sake, I've also included jpeg
and it can obviously be easily extended just for any extension, including but not limited to images.
If there are query strings or such in the image URLs, you can filter it out easily in isRequestImage:
method, I just didn't have any so I didn't need it.
Upvotes: 2