UIWebView未调用我的Javascript函数
我知道这个问题已经贴了很多次了。但他们都没有帮我解决我的问题。请在下投票前考虑阅读整个问题:-(<)/P> 所以,我有下面几行代码UIWebView未调用我的Javascript函数,javascript,html,ios,objective-c,uiwebview,Javascript,Html,Ios,Objective C,Uiwebview,我知道这个问题已经贴了很多次了。但他们都没有帮我解决我的问题。请在下投票前考虑阅读整个问题:-( 所以,我有下面几行代码 - (void)viewDidLoad { [super viewDidLoad]; NSURL * url = [NSURL URLWithString: @"https://www.w3schools.com/code/tryit.asp?filename=FEGU9IV4SAK8"]; NSURLRequest * request = [NSU
- (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] 能够从中提示“Hello”
[webView stringByEvaluatingJavaScriptFromString:@“警报('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>
页面标题
我的标题1
点击我!
功能测试(){
警报(“启动”);
}
请帮助我找出HTML方面缺少的内容?还是用我的母语Objc?
编辑1:
正如@Andy所建议的,我从本地加载了html。然后我可以调用JS函数“test()”您不应该使用w3schools编辑器作为项目的源html。您试图访问的url
不仅包含您的内容,还包含W3S学校使用的脚本。相反,您应该将html文件放在自己的服务器上,或者在项目中放一个.html文件。然后,您可以调用test()
方法。“test()”不是从本机代码调用的。这有帮助吗@是的,的确如此!!!从本地加载html时会调用JS。嘿@chengsam,你说得对!当从loal(主捆绑包)加载相同的html时,它会工作