UIWebView使用elementFromPoint()获取图像网址

时间:2013-08-14 18:38:20

标签: javascript ios cocoa-touch uiwebview uiimage

我正在尝试使用UILongPressGestureRecognizer在UIWebView中获取图像的网址。

我有点工作,但我不确定坐标是否关闭,或者它只是没有在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中单击网页上的某个点,我会得到以下结果: 滚动:0 单击pointY:89 Y * = scale + = scrollY = 86.8293

现在如果我向上滚动页面,那么我点击的点与顶部一致(大约在y = 0)我得到这些结果: 滚动:144 单击pointY:1 Y * = scale + = scrollY = 144.976

现在在计算之前,滚动似乎已关闭。该点为89,但滚动到该点时,滚动条为144.为什么会这样?

我从window.pageYOffset

获取滚动

3 个答案:

答案 0 :(得分: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;}

答案 1 :(得分:1)

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

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

我做了什么:

在每个图片<img... html DOM元素上,我将onClick javascript处理程序更改为window.location

f.e

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

UIWebView委托的方法中忽略上面的链接,但是,我们可以获取图片网址。

- (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?

答案 2 :(得分: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使用其他替代事件。