在iOS 8中使用WKWebView,如何从本机端运行JavaScript函数或以其他方式从本机端到JavaScript进行通信?似乎没有类似于UIWebView的stringByEvaluatingJavaScriptFromString:
。
(我可以在- addScriptMessageHandler:name:
对象上使用configuration.userContentController
来允许从JS到本地的通信,但我正在寻找相反的方向。)
答案 0 :(得分:52)
(我在这里提出问题之后不久就提交了雷达。)
几天前刚刚添加了一种新方法(感谢jcesarmobile指出它):
添加
-[WKWebView evaluateJavaScript:completionHandler:]
http://trac.webkit.org/changeset/169765
该方法适用于iOS 8 beta 3及更高版本。这是新方法签名:
/* @abstract Evaluates the given JavaScript string.
@param javaScriptString The JavaScript string to evaluate.
@param completionHandler A block to invoke when script evaluation completes
or fails.
@discussion The completionHandler is passed the result of the script evaluation
or an error.
*/
- (void)evaluateJavaScript:(NSString *)javaScriptString
completionHandler:(void (^)(id, NSError *))completionHandler;
文档位于此处:https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript。
答案 1 :(得分:20)
将脚本插入到将在WKWebView中显示的页面中。此脚本将返回页面URL(但您可以编写另一个JavaScript代码)。这意味着脚本事件是在网页上生成的,但它将在我们的函数中处理:
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {...}
extension WKUserScript {
enum Defined: String {
case getUrlAtDocumentStartScript = "GetUrlAtDocumentStart"
case getUrlAtDocumentEndScript = "GetUrlAtDocumentEnd"
var name: String { return rawValue }
private var injectionTime: WKUserScriptInjectionTime {
switch self {
case .getUrlAtDocumentStartScript: return .atDocumentStart
case .getUrlAtDocumentEndScript: return .atDocumentEnd
}
}
private var forMainFrameOnly: Bool {
switch self {
case .getUrlAtDocumentStartScript: return false
case .getUrlAtDocumentEndScript: return false
}
}
private var source: String {
switch self {
case .getUrlAtDocumentEndScript, .getUrlAtDocumentStartScript:
return "webkit.messageHandlers.\(name).postMessage(document.URL)"
}
}
fileprivate func create() -> WKUserScript {
return WKUserScript(source: source,
injectionTime: injectionTime,
forMainFrameOnly: forMainFrameOnly)
}
}
}
extension WKWebViewConfiguration {
func add(script: WKUserScript.Defined, scriptMessageHandler: WKScriptMessageHandler) {
userContentController.addUserScript(script.create())
userContentController.add(scriptMessageHandler, name: script.name)
}
}
Init WKWebView
let config = WKWebViewConfiguration()
config.add(script: .getUrlAtDocumentStartScript, scriptMessageHandler: self)
config.add(script: .getUrlAtDocumentEndScript, scriptMessageHandler: self)
webView = WKWebView(frame: UIScreen.main.bounds, configuration: config)
webView.navigationDelegate = self
view.addSubview(webView)
抓住事件
extension ViewController: WKScriptMessageHandler {
func userContentController (_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if let script = WKUserScript.Defined(rawValue: message.name),
let url = message.webView?.url {
switch script {
case .getUrlAtDocumentStartScript: print("start: \(url)")
case .getUrlAtDocumentEndScript: print("end: \(url)")
}
}
}
}
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
private var webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
let config = WKWebViewConfiguration()
config.add(script: .getUrlAtDocumentStartScript, scriptMessageHandler: self)
config.add(script: .getUrlAtDocumentEndScript, scriptMessageHandler: self)
webView = WKWebView(frame: UIScreen.main.bounds, configuration: config)
webView.navigationDelegate = self
view.addSubview(webView)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
webView.load(urlString: "http://apple.com")
}
}
extension ViewController: WKScriptMessageHandler {
func userContentController (_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if let script = WKUserScript.Defined(rawValue: message.name),
let url = message.webView?.url {
switch script {
case .getUrlAtDocumentStartScript: print("start: \(url)")
case .getUrlAtDocumentEndScript: print("end: \(url)")
}
}
}
}
extension WKWebView {
func load(urlString: String) {
if let url = URL(string: urlString) {
load(URLRequest(url: url))
}
}
}
extension WKUserScript {
enum Defined: String {
case getUrlAtDocumentStartScript = "GetUrlAtDocumentStart"
case getUrlAtDocumentEndScript = "GetUrlAtDocumentEnd"
var name: String { return rawValue }
private var injectionTime: WKUserScriptInjectionTime {
switch self {
case .getUrlAtDocumentStartScript: return .atDocumentStart
case .getUrlAtDocumentEndScript: return .atDocumentEnd
}
}
private var forMainFrameOnly: Bool {
switch self {
case .getUrlAtDocumentStartScript: return false
case .getUrlAtDocumentEndScript: return false
}
}
private var source: String {
switch self {
case .getUrlAtDocumentEndScript, .getUrlAtDocumentStartScript:
return "webkit.messageHandlers.\(name).postMessage(document.URL)"
}
}
fileprivate func create() -> WKUserScript {
return WKUserScript(source: source,
injectionTime: injectionTime,
forMainFrameOnly: forMainFrameOnly)
}
}
}
extension WKWebViewConfiguration {
func add(script: WKUserScript.Defined, scriptMessageHandler: WKScriptMessageHandler) {
userContentController.addUserScript(script.create())
userContentController.add(scriptMessageHandler, name: script.name)
}
}
添加Info.plist传输安全设置
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
答案 2 :(得分:5)
这可能不是一种理想的方法,但根据您的使用情况,您可以在感染用户脚本后重新加载WKWebView:
NSString *scriptSource = @"alert('WKWebView JS Call!')";
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:scriptSource
injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
forMainFrameOnly:YES];
[wkWebView.configuration.userContentController addUserScript:userScript];
[wkWebView reload];
答案 3 :(得分:2)
这里有一些为我工作的东西:
在WKWebView上创建一个扩展,用于定义&#39; runJavaScriptInMainFrame:&#39;方法。在扩展方法中,使用NSInvocationOperation来调用未记录的&#39; _runJavaScriptInMainFrame:&#39;方法
extension WKWebView {
func runJavaScriptInMainFrame(#scriptString: NSString) -> Void {
let selector : Selector = "_runJavaScriptInMainFrame:"
let invocation = NSInvocationOperation(target: self, selector: selector, object: scriptString)
NSOperationQueue.mainQueue().addOperation(invocation)
}
}
要使用,请致电:
webview.runJavacriptInMainFrame:(scriptString: "some javascript code")
感谢Larsaronen提供了WKWebView私有API的链接。
答案 4 :(得分:0)
我刚开始自己挖掘WKWebView API,所以这可能不是最好的方法,但我认为你可以使用以下代码来实现:
NSString *scriptSource = @"console.log('Hi this is in JavaScript');";
WKUserScript *userScript = [[WKUserScript alloc]
initWithSource:scriptSource
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:YES];
[myWKController addUserScript:userScript];
(来自WWDC'14的演讲)
答案 5 :(得分:0)
谣言认为这是一个错误,因为有一个私有函数类似于(?)UIWebView中公开可用来评估来自obj-C的javascript。
答案 6 :(得分:0)
方法示例,运行 JS 代码以从 base64String 加载 .pdf
TextField(
controller: myControllers[index],
),