1.在iOS中更改JS的內容
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="word">哈哈哈哈哈哈哈哈.哈哈哈呵呵</p>
<ul>
<li class="change">你好</li>
<li>我好</li>
<li>你們好</li>
<li>纔是真的好</li>
</ul>
<img src="img_04.jpg">
</body>
</html>
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.webView.delegate = self;
[self.webView loadRequest:request];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//刪除
NSString *str1 = @"var word = document.getElementById('word');";
NSString *str2 = @"word.remove();";
[webView stringByEvaluatingJavaScriptFromString:str1];
[webView stringByEvaluatingJavaScriptFromString:str2];
//更改
NSString *str3 = @"var change = document.getElementsByClassName('change')[0];"
"change.innerHTML = '好你的哦!';";
[webView stringByEvaluatingJavaScriptFromString:str3];
//插入
NSString *str4 = @"var img = document.createElement('img');"
"img.src = 'img_04.jpg';"
"document.body.appendChild(img);";
[webView stringByEvaluatingJavaScriptFromString:str4];
2.JS調用iOS代碼
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<br>
<p></p>
<button onclick="openCamera();">訪問相冊</button>
<button onclick="openCamera1();">訪問相冊</button>
<button onclick="openCamera2();">訪問相冊</button>
<button onclick="openCamera3();">訪問相冊</button>
<a href="http://baidu.com">百度</a>
<script>
function openCamera(){
window.location.href = 'xmg?openCamera?numbers=5';
}
function openCamera1(){
window.location.href = 'xmg://phone';
}
function openCamera2(){
window.location.href = 'xmg://sendMessage';
}
</script>
</body>
</html>
思想:點擊了網頁的按鈕,就能夠調用iOS的照相。通處就是JS響應,返回數據給iOS,iOS接收到再處理
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
- (BOOL)webView:(nonnull UIWebView *)webView shouldStartLoadWithRequest:(nonnull NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *url = request.URL.absoluteString;
NSRange range = [url rangeOfString:@"xmg://"];
NSUInteger location = range.location;
// xmg://openCamera
if (location != NSNotFound) {
NSString *str = [url substringFromIndex:location + range.length];
NSLog(@"%@", str);
SEL sel = NSSelectorFromString(str);
[self performSelector:sel withObject:nil];
}
return YES;
}
/**
* 訪問相冊
*/
-(void)openCamera{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}