[英]Call JavaScript from Objective-C in AppDelegate
有什么方法可以从Objective-C调用设备令牌吗?
我只是创建了cordova ios项目,因为我只有Objective-C的基础知识。 它将自动生成AppDelegate.m
类
@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
self.viewController = [[MainViewController alloc] init];
NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"];
[webView stringByEvaluatingJavaScriptFromString:jsCallBack];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
如何从inappbrowser中加载的index.html文件调用javascript函数
<!DOCTYPE html>
<html>
<head>
<title>Device Ready Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
myFunction()
{
alert('called');
}
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// device APIs are available
//
function onDeviceReady() {
// Now safe to use device APIs
}
</script>
</head>
<body onload="onLoad()">
</body>
</html>
首先:
确保您的Web视图已经加载了HTML页面(以防您还需要修改DOM中的某些UI元素,它可能也应该已经呈现。加载本身是异步执行的。这意味着您无法一次实现它处理,但必须等到准备好进行操作为止。
当您通过注入应用程序的start方法调用该函数时,我认为尚未准备好Webview。
而是对iOS应用程序使用Delegate的方法: https : //developer.apple.com/reference/uikit/uiwebviewdelegate
UIWebViewDelegate通知您某些状态(更改)。 例如:
因此,我建议使用以下委托属性扩展您的AppDelegate(或创建一个新的委托):
@property (nonatomic) UIWebViewDelegate *webDelegate;
相应地设置webView的委托:
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
self.viewController = [[MainViewController alloc] init];
// I just used your very own code for this, I think you will have a separate property for this webView ?
webView.delegate = self;
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
并实现一个webview委托方法(在这种情况下,当一个webview完成加载时:
@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
...
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"];
[webView stringByEvaluatingJavaScriptFromString:jsCallBack];
}
@end
您可以在目标C的任何位置调用javascript函数:
NSString *str=@"window['function_name'].apply(window,['param1','param2'])";
[webview evaluateJavaScript:str completionHandler:nil];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.