gpt4 book ai didi

javascript - swift WebView : How to call correctly swift code from javascript?

转载 作者:IT王子 更新时间:2023-10-29 05:11:19 25 4
gpt4 key购买 nike

我试图让我的 javascript 与 swift 代码交互,但不幸的是我没有成功。

目前,我只是尝试更改标题颜色并显示一条消息,就像您将在下面的代码中看到的那样。

这是我的 (index.html) 代码:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
</head>
<body>
<h1>WebView Test</h1>
<script type="text/javascript" src="main.js"></script>
</body>
</html>

这是我的 (ma​​in.js -JavaScript) 代码:

function callNativeApp () {
try {
webkit.messageHandlers.callbackHandler.postMessage("Send from JavaScript");
} catch(err) {
console.log('error');
}
}

setTimeout(function () {
callNativeApp();
}, 5000);

function redHeader() {
document.querySelector('h1').style.color = "red";
}

这是我的 (ViewController.swift) 代码:

import UIKit
import WebKit

class ViewController: UIViewController, WKScriptMessageHandler {

@IBOutlet var containerView : UIView! = nil

var webView: WKWebView?

override func loadView() {
super.loadView()

var contentController = WKUserContentController();
var userScript = WKUserScript(
source: "redHeader()",
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
forMainFrameOnly: true
)
contentController.addUserScript(userScript)
contentController.addScriptMessageHandler(
self,
name: "callbackHandler"
)

var config = WKWebViewConfiguration()
config.userContentController = contentController

self.webView = WKWebView()
self.view = self.webView!
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("index", ofType: "html")!)
var req = NSURLRequest(URL: url)
self.webView!.loadRequest(req)
}

func userContentController(userContentController: WKUserContentController!,didReceiveScriptMessage message: WKScriptMessage!) {
if(message.name == "callbackHandler") {
println("JavaScript is sending a message \(message.body)")
} }

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}

最佳答案

您已正确设置所有内容,但您没有将 WKWebViewConfiguration 实例提供给 WKWebView。由于配置中有 Javascript/Swift 桥接器的细节,所以不能来回说。

override func loadView() {
// ...
var config = WKWebViewConfiguration()
config.userContentController = contentController

self.webView = WKWebView(frame: self.view.frame, configuration: config)
self.view = self.webView!
}

关于javascript - swift WebView : How to call correctly swift code from javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25827368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com