转载自: http://stackoverflow.com/questions/18239666/uiwebview-getting-image-url-with-elementfrompoint
- (void)longPressRecognized:(UILongPressGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint point = [gestureRecognizer locationInView:webView];
longpressTouchedPoint = point;
// convert point from view to HTML coordinate system
CGSize viewSize = [webView frame].size;
CGSize windowSize = [webView windowSize];
CGFloat f = windowSize.width / viewSize.width;
if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.) {
point.x = point.x * f;
point.y = point.y * f;
} else {
// On iOS 4 and previous, document.elementFromPoint is not taking
// offset into account, we have to handle it
CGPoint offset = [webView scrollOffset];
point.x = point.x * f + offset.x;
point.y = point.y * f + offset.y;
}
// Load the JavaScript code from the Resources and inject it into the web page
NSString *path = [[NSBundle mainBundle] pathForResource:@"JSTools" ofType:@"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString: jsCode];
// call js functions
NSString *tags = [webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:@"getHTMLElementsAtPoint(%i,%i);",(NSInteger)point.x,(NSInteger)point.y]];
NSString *tagsSRC = [webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:@"getLinkSRCAtPoint(%i,%i);",(NSInteger)point.x,(NSInteger)point.y]];
NSLog(@"src : %@",tags);
NSLog(@"src : %@",tagsSRC);
NSString *url = nil;
if ([tags rangeOfString:@",IMG,"].location != NSNotFound) {
url = tagsSRC; // Here is the image url!
}
function getHTMLElementsAtPoint(x,y) {
var tags = "";
var e;
var offset = 0;
while ((tags.search(",(A|IMG),") < 0) && (offset < 20)) {
tags = ",";
e = document.elementFromPoint(x,y+offset);
while (e) {
if (e.tagName) {
tags += e.tagName + ',';
}
e = e.parentNode;
}
if (tags.search(",(A|IMG),") < 0) {
e = document.elementFromPoint(x,y-offset);
while (e) {
if (e.tagName) {
tags += e.tagName + ',';
}
e = e.parentNode;
}
}
offset++;
}
return tags;}
function getLinkSRCAtPoint(x,y) {
var tags = "";
var e = "";
var offset = 0;
while ((tags.length == 0) && (offset < 20)) {
e = document.elementFromPoint(x,y+offset);
while (e) {
if (e.src) {
tags += e.src;
break;
}
e = e.parentNode;
}
if (tags.length == 0) {
e = document.elementFromPoint(x,y-offset);
while (e) {
if (e.src) {
tags += e.src;
break;
}
e = e.parentNode;
}
}
offset++;
}
return tags;}