iOS中動態注入JavaScript方法。動態給html標籤添加事件

項目中有這樣一種需求,給html5網頁中圖片添加點擊事件,而且彈出彈出點擊的對應的圖片,而且能夠保持圖片到本地

應對這樣的需求你可能會想到不少方法來實現。

1. 最簡單的方法就是在html5中添加圖片的onClick方法,並把圖片的src和index傳過來。這種方法雖然可以很好的解決這個問題,可是還須要前端代碼的支持
2.使用WebviewJavascripBridge添加objc和js交互的方法,經過調用方法來實現效果,缺點是須要用到第三方,而且一樣也須要前端代碼的支持
3.第三種也就是今天這裏要着重介紹的方法:objc中動態注入JavaScript代碼,動態給img標籤添加onClick事件。話很少說,直接上代碼(最後有demo下載地址)

html代碼css

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title>測試demo</title>
        <style type="text/css">
            img {
                width: 100%;
            }
        </style>
    </head>

    <body>
        <p>內容測試我是詳情內容1</p>
        <img src="http://img1.cyzone.cn/uploadfile/2017/0602/20170602094901601.jpg">
        <p>內容測試我是詳情內容2</p>
        <p>內容測試我是詳情內容3</p>
        <img src="http://img1.cyzone.cn/uploadfile/2017/0602/20170602094902133.jpg">
        <p>內容測試我是詳情內容4</p>
        <img src="http://img1.cyzone.cn/uploadfile/2017/0602/20170602094902734.jpg">
        <p>內容測試我是詳情內容5</p>
        
    </body>

</html>

objc代碼html

//
//  ViewController.m
//  JSInsertDemo
//
//  Created by Tiny on 2017/6/8.
//  Copyright © 2017年 LOVEGO. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIWebViewDelegate>

@property (nonatomic,strong) UIWebView *webView;
@property (nonatomic,strong) NSMutableArray *imgsArr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.imgsArr = [NSMutableArray array];
    
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.20.14:8020/JsToObjc/index.html"]]
    //加載本地html
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [self.webView loadRequest:request];
}

-(UIWebView *)webView{
    if (_webView == nil) {
        _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        _webView.delegate = self;
        _webView.scrollView.scrollsToTop = NO;
        _webView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_webView];
    }
    return _webView;
}


#pragma mark - webViewDelegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    if([request.URL.scheme isEqualToString:@"image-preview"]){
        //觸發點擊事件  -- >拿到是第幾個標籤被點擊了
        NSString *clickImg = request.URL.resourceSpecifier;
        //遍歷數組,查詢查找當前第幾個圖被點擊了
        NSInteger selectIndex = 0;
        for(int i = 0; i< self.imgsArr.count;i++){
            NSString *imgUrl = self.imgsArr[i];
            if ([imgUrl isEqualToString:clickImg]) {
                selectIndex = i;
                break;
            }
        }
        //拿到當前選中的index  -- > 使用圖片瀏覽器讓圖片顯示出來
        NSLog(@"當前圖片%@ 選中index:%zi",clickImg,selectIndex);
        return NO;
    }
    return YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    //加載完成以後開始注入js事件
    [self.webView stringByEvaluatingJavaScriptFromString:@"\
     function imageClickAction(){\
        var imgs=document.getElementsByTagName('img');\
        var length=imgs.length;\
        for(var i=0;i<length;i++){\
            img=imgs[i];\
            img.onclick=function(){\
                window.location ='image-preview:'+this.src;\
            }\
        }\
     }\
     "];
    //觸發方法 給全部的圖片添加onClick方法
    [self.webView stringByEvaluatingJavaScriptFromString:@"imageClickAction();"];
    
    //拿到最終的html代碼
//    NSString *HTMLSource = [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('script')[0].innerHTML"];
    //調用html代碼
    [self.webView stringByEvaluatingJavaScriptFromString:@"sendMsg('我是objc傳入的值');"];

    //拿到全部img標籤對應的圖片
    [self handleImgLabel];
}

-(void)handleImgLabel{
    //要拿到全部img標籤對應的圖片的src
    //1.拿到img標籤的個數
    NSUInteger length = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('img').length"] integerValue];
    //2.遍歷標籤,拿到標籤中src的內容
    for (int i =0 ; i < length; i++) {
        NSString *jsStr = [NSString stringWithFormat:@"document.getElementsByTagName('img')[%zi].src",i];
        NSString *img = [self.webView stringByEvaluatingJavaScriptFromString:jsStr];
        //3.將標籤中src內容存入數組
        [self.imgsArr addObject:img];
    }
}
@end

demo下載地址:https://github.com/qqcc1388/ObjcInsetJavaScriptDemo前端

轉載請標註來源https://www.cnblogs.com/qqcc1388/p/6962895.htmlhtml5

相關文章
相關標籤/搜索