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


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

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

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

html代碼

<!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代碼

//
//  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.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM