Similar to a regular js file that starts with referenced external query and then your js custom code, I need to do the same in Swift using JavascriptCore.
类似于从引用外部查询开始的普通js文件,然后是js自定义代码,我需要使用JavascriptCore在Swift中执行相同的操作。
I saw this Objective-C example:
我看到了Objective-C的例子
NSURL *scriptURL = [NSURL URLWithString:@"path/to/fancyLibrary.js"];
NSError *error = nil;
NSString *script = [NSString stringWithContentsOfURL:scriptURL encoding:NSUTF8StringEncoding error:&error];
[context evaluateScript:script];
It does the first part of bringing down an external js file, but I want to also add a js block calling some of the functions in that referenced file. How do I do that!? Can you do it in Swift?
它完成了取出一个外部js文件的第一部分,但是我还想添加一个js块来调用该引用文件中的一些函数。我该怎么做!?你能用斯威夫特写吗?
2 个解决方案
#1
1
you can just call evaluateJavascript
on the webView to call functions and get information, so you can do things like:
你可以在webView上调用evaluateJavascript来调用函数并获取信息,你可以这样做:
webView.evaluateJavascript("someFuncton();") { (result, error) in
if (!error) {
print(result(
}
}
webView.evaluateJavascript("document.height") { (result, error) in
if (!error) {
print(result(
}
}
You can even post messages from the Javascript back to native swift functions using webKit using message hanlders. see this ref
您甚至可以使用webKit使用消息hanlders将来自Javascript的消息发送回本地swift函数。看到这个裁判
Here is an objective-c guide on sending messages both ways using Javascript
这里有一个objective-c指南,可以用Javascript来发送消息。
#2
0
For a complete answer, you want to: 1. inherit from WKNavigationDelegate 2. in viewDidLoad:
要得到完整的答案,你需要:1。继承WKNavigationDelegate 2。在viewDidLoad:
self.webView.navigationDelegate = self
3. and calling it in the didFinishNavigation, see this
3所示。在didFinishNavigation中调用它,看到这个
#1
1
you can just call evaluateJavascript
on the webView to call functions and get information, so you can do things like:
你可以在webView上调用evaluateJavascript来调用函数并获取信息,你可以这样做:
webView.evaluateJavascript("someFuncton();") { (result, error) in
if (!error) {
print(result(
}
}
webView.evaluateJavascript("document.height") { (result, error) in
if (!error) {
print(result(
}
}
You can even post messages from the Javascript back to native swift functions using webKit using message hanlders. see this ref
您甚至可以使用webKit使用消息hanlders将来自Javascript的消息发送回本地swift函数。看到这个裁判
Here is an objective-c guide on sending messages both ways using Javascript
这里有一个objective-c指南,可以用Javascript来发送消息。
#2
0
For a complete answer, you want to: 1. inherit from WKNavigationDelegate 2. in viewDidLoad:
要得到完整的答案,你需要:1。继承WKNavigationDelegate 2。在viewDidLoad:
self.webView.navigationDelegate = self
3. and calling it in the didFinishNavigation, see this
3所示。在didFinishNavigation中调用它,看到这个