【发布时间】:2014-12-22 14:50:52
【问题描述】:
我正在制作一个使用 WKWebView 的应用程序,我需要能够获取页面上任何 HTML 元素的 URL。例如,假设用户访问谷歌图像并长按图像,我需要能够找到该图像的完整 URL。
有人知道怎么做吗?
谢谢!
【问题讨论】:
我正在制作一个使用 WKWebView 的应用程序,我需要能够获取页面上任何 HTML 元素的 URL。例如,假设用户访问谷歌图像并长按图像,我需要能够找到该图像的完整 URL。
有人知道怎么做吗?
谢谢!
【问题讨论】:
此行为可以通过以下 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) 从Objective-C(或Swift)执行imageSourceFromPoint 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
看起来像这样:
希望对你有所帮助。
【讨论】: