5

我正在尝试使用 UILongPressGestureRecognizer 获取在 UIWebView 中点击的图像的 url。

我有点工作,但我不确定坐标是否关闭,或者它只是没有在 DOM 中找到 img 标签,因为它并不总是有效。

我正在使用这段代码:

int displayWidth = [[self.webView stringByEvaluatingJavaScriptFromString:@"window.outerWidth"] intValue];
CGFloat scale = self.webView.frame.size.width / displayWidth;
CGPoint pt = [gesture locationInView:self.webView];
pt.x /= scale;
pt.y /= scale;
NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).parentElement.getElementsByTagName(\"img\")[0].src", pt.x, pt.y];
NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:imgURL];

如果我使用的网站开始时缩小并在网格中包含图像,然后放大然后选择图像,我会在页面的左上角得到图像,而不是单击的图像。不确定是缩放问题、偏移问题还是 DOM 问题?

编辑 - - - - - -

对于初学者来说,坐标肯定是关闭的!如果我在 UIWebView 中单击网页上的一个点,我会得到以下结果: ScrollY: 0 Click pointY: 89 Y *= scale += scrollY = 86.8293

现在,如果我向上滚动页面,所以我点击的点与顶部一致(大约在 y=0 处)我得到以下结果: ScrollY: 144 Click pointY:1 Y *= scale += scrollY = 144.976

现在在计算之前,滚动似乎关闭了。该点是 89,但当滚动到该点时,滚动显示为 144。为什么会这样?

我从 window.pageYOffset 得到滚动

4

3 回答 3

6

将这 2 个 javascript 函数放在一个名为 JSTools.js 的文件中

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;}

然后在你的控制器中

- (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!
    }

来自多个来源的混合,归功于网络社区!

编辑

您还必须使用这两个功能在 uiwebview 上创建一个类别:

- (CGSize)windowSize {
CGSize size;
size.width = [[self stringByEvaluatingJavaScriptFromString:@"window.innerWidth"] integerValue];
size.height = [[self stringByEvaluatingJavaScriptFromString:@"window.innerHeight"] integerValue];
return size;}

- (CGPoint)scrollOffset {
CGPoint pt;
pt.x = [[self stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] integerValue];
pt.y = [[self stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] integerValue];
return pt;}
于 2013-08-22T14:07:12.980 回答
1

我最近实现了一个类似的目标,但我没有确定“触摸”坐标。

如果您有权修改 html/javascript 源代码,我的回答会有所帮助。

我做了什么:

在每个图像<img...html DOM 元素上,我放置了onClickjavascript 处理程序来更改window.location

javascript function clickedImage(imageURL) {
    window.location = "customScheme://"+imageURL; // attached image url to be able to read it inside `UIWebView`
}

UIWebView委托的方法上,忽略上面的链接,但是,我们能够获取图像 URL。

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

  if ([[request.URL scheme] isEqualToString:@"customScheme"]) {
        //Fetching image URL
        NSLog(@"Clicked on image with URL %@", [request.URL host])
        ...
        // Always return NO not to allow `UIWebView` process such links
        return NO; 
    }
    ....
}

抱歉,如果这种方法不完全适合您的问题,但我想这是您可以遵循并深入挖掘的选项。

小提示:使用UILongPressGestureRecognizer你可以通过制作 javascript 来模拟这种行为: Long Press in JavaScript?

于 2013-08-21T10:22:16.017 回答
1

您可以通过以下代码获取元素

        <script type="text/javascript">

            (function($) {
             $.fn.longClick = function(callback, timeout) {
             var timer;
             timeout = timeout || 500;
             $(this).mousedown(function(e) {
                               timer = setTimeout(function() { callback(e.offsetX,e.offsetY); }, timeout);
                               return false;
                               });
             $(document).mouseup(function() {
                                 clearTimeout(timer);
                                 return false;
                                 });
             };

             })(jQuery);


            $(window).longClick(function(x,y)
            {
              var element = document.elementFromPoint(x, y);
              alert(nodeToString(element));
            },600);


            function nodeToString ( node ) {
                var tmpNode = document.createElement( "div" );
                tmpNode.appendChild( node.cloneNode( true ) );
                var str = tmpNode.innerHTML;
                tmpNode = node = null; // prevent memory leaks in IE
                return str;
            }
        </script>

这只是js代码。mousedown 和 mouseup 不适用于 ios 。您需要为 ios webView 使用其他替代事件。

于 2013-08-22T15:30:44.203 回答