此行为可以通过以下 4 个步骤来完成:
1)添加UILongPressGestureRecognizer
到您的WKWebView
实例中,不要忘记让您的识别器与自己的WKWebView
手势识别器同时识别:
SEL selector = @selector(handleLongPressGestureRecognizer:);
UILongPressGestureRecognizer* gestuRecognizer =
[[UILongPressGestureRecognizer alloc] initWithTarget:self
action:selector];
gestuRecognizer.delegate = self;
[webView addGestureRecognizer:gestuRecognizer];
<...>
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:
(UIGestureRecognizer*)otherGestureRecognizer {
return YES;
}
2)大致像这样创建JavaScript文件(tools.js):
function imageSourceFromPoint(x, y) {
var element = document.elementFromPoint(x, y);
if (element.tagName == 'IMG' && element.src) {
return element.src;
}
return null;
}
3) 将该 tools.js 加载到您的网页中。这可以直接在handleLongPressGestureRecognizer
方法中完成,例如:
- (void)handleLongPressGestureRecognizer:
(UILongPressGestureRecognizer*)recognizer {
if (recognizer.state == UIGestureRecognizerStateBegan) {
[self loadJavaScriptFileIfNeededWithCompletion:^{
<...>
}];
}
}
- (void)loadJavaScriptFileIfNeededWithCompletion:(void(^)())completion {
<...>
[self.webView evaluateJavaScript:[self toolsJavaScriptFile]
completionHandler:^(id result, NSError* error) {
completion();
}];
<...>
}
- (NSString*)toolsJavaScriptFile {
NSString* path = [[NSBundle mainBundle] pathForResource:@"tools"
ofType:@"js"];
return [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
}
4)imageSourceFromPoint
使用长按手势的位置从 Objective-C(或 Swift)执行 JavaScript 函数:
- (void)handleLongPressGestureRecognizer:
(UILongPressGestureRecognizer*)recognizer {
<...>
[self loadJavaScriptFileIfNeededWithCompletion:^{
CGPoint touchPoint = [recognizer locationInView:self.webView];
[self imageSourceFromPoint:touchPoint completion:^(NSString* source) {
<...>
}];
}];
<...>
}
- (void)imageSourceFromPoint:(CGPoint)point
completion:(void(^)(NSString*))completion {
NSString* jsCode = [NSString stringWithFormat:
@"imageSourceFromPoint(%g, %g)", point.x, point.y];
[self.webView evaluateJavaScript:jsCode
completionHandler:^(id result, NSError* error) {
<...>
NSString* resultString = (NSString*)result;
completion(resultString);
}];
}
请注意,省略了一堆错误检查,您可以在此处找到完整的项目示例https://dl.dropboxusercontent.com/u/930742/so/GetHTMLElement.zip
它看起来像这样:
我希望这能帮到您。