gpt4 book ai didi

html - WebKit获取元素URL? iOS8

转载 作者:行者123 更新时间:2023-12-01 18:12:36 27 4
gpt4 key购买 nike

我正在制作一个使用WKWebView的应用程序,我需要能够获取页面上任何HTML元素的URL。例如,假设用户转到Google图片并在图片上长按,我需要能够找到该图片的完整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

看起来像这样:

我希望这能帮到您。

关于html - WebKit获取元素URL? iOS8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27605026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com