要調用的Objective-C的方法在JS:
以下網址可以幫助這樣做
How to invoke Objective C method from Javascript and send back data to Javascript in iOS?
沒有執行的方式,我們通過導航到其他頁面做的解決方法在導航過程中,webview委託會監視導航的前綴並執行我們指定的方法。
sample.html
<html>
<head>
<script type='text/javascript'>
function getText()
{
return document.getElementById('txtinput').value;
}
function locationChange()
{
window.location = 'ios:webToNativeCall';
}
</script>
</head>
<body style='overflow-x:hidden;overflow-y:hidden;'>
<h2 style = "font-size:16px;" align='center'>Hi Welcome to Webpage</h2>
<br/>
<p align='center' style = "font-size:12px;">Please Click the button after entering the text</p>
<br/>
<center>
<input type='text' style='width:90px;height:30px;' id='txtinput'/>
</center>
<br/>
<center>
<input type='button' style='width:90px;height:30px;' onclick='locationChange()' value='click me'>
</center>
</body>
</html>
Objective-C代碼當你在HTML頁面中單擊按鈕下面的委託
將發射和導航取消,因爲我們返回NO和相應的方法被調用
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if ([[[request URL] absoluteString] hasPrefix:@"ios:"]) {
// Call the given selector
[self performSelector:@selector(webToNativeCall)];
// Cancel the location change
return NO;
}
return YES;
}
- (void)webToNativeCall
{
NSString *returnvalue = [self.webviewForHtml stringByEvaluatingJavaScriptFromString:@"getText()"];
self.valueFromBrowser.text = [NSString stringWithFormat:@"From browser : %@", returnvalue ];
}
小心安全隱患! – Gustav 2015-01-17 14:17:34
你能更詳細地瞭解它嗎? – Vinodh 2015-01-19 10:12:25
假設你的類中有一個名爲getSecretToken的方法。那麼你可以從Javascript中調用它 – Gustav 2015-01-19 12:40:51