我知道這個問題已經發布很多次了。但他們都沒有幫助我解決我的問題。請考慮downvote之前閱讀整個問題:-)UIWebView不能調用我的Javascript函數
所以,我有如下所以,到目前爲止,我已經試過/理解代碼
- (void)viewDidLoad {
[super viewDidLoad];
NSURL * url = [NSURL URLWithString: @"https://www.w3schools.com/code/tryit.asp?filename=FEGU9IV4SAK8"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
self.webView.delegate = self;
[self.webView loadRequest:request];
}
#pragma mark - UIWebView Delegates
- (void) webViewDidFinishLoad:(UIWebView *)webView {
NSString * jsString = [NSString stringWithFormat:@"test()"];
[webView stringByEvaluatingJavaScriptFromString:jsString] ;
//This code is working. Able to prompt "Hello"
// jsString = [NSString stringWithFormat:@"alert('Hello');"];
// [webView stringByEvaluatingJavaScriptFromString:jsString] ;
}
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType;
{
// ignore legit webview requests so they load normally
if (![request.URL.scheme isEqualToString:kSchemeName]) {
return YES;
}
// look at the actionType and do whatever you want here
if ([actionType isEqualToString:kJSActionForPay]) {
//Call objective-c method - Success
}
// make sure to return NO so that your webview doesn't try to load your made-up URL
return NO;
}
線。
[1]僅在Web視圖加載後調用JS函數。 (使用代表)
[2]可以從提示 「你好」
[webView stringByEvaluatingJavaScriptFromString:@"alert('Hello')"] ;
[3]的變化在HTML端完成
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
<script>
function test() {
alert("Started");
}
</script>
</html>
請幫忙找出我我在HTML端缺少?或在我的本地Objc?
編輯1: 作爲@Andy建議,我從本地加載html。然後我可以調用JS函數「test()」
「test()」不從本地代碼調用。 –
完全可以幫到你嗎? http://stackoverflow.com/questions/14334047/how-to-call-javascript-function-in-objective-c –
@AndyDonegan是的,它確實!它從本地加載html時調用JS。 –