从UITextField发送字符串Hi到本地HTML并以HTML格式显示然后从HTML发送hello,并且应该使用WKScriptMessageHandler在UILabel中更新
答案 0 :(得分:0)
请找到以下代码
GetValue.js -
var returnedValue = "";
function display(val){
var value = true;
try {
webkit.messageHandlers.reciever.postMessage(value);
} catch(err) {
console.log('error');
}
returnedValue = val;
document.getElementById("demo").innerHTML = returnedValue;
}
PostValue.js
function myFunction() {
var value = document.getElementById("name").value;
try {
webkit.messageHandlers.scriptHandler.postMessage(value);
} catch(err) {
console.log('error');
}
}
WebPage.html -
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width">
<meta name="viewport" content="initial-scale=1.5">
<head>
<script type="text/javascript" src="postValue.js" charset="utf-8"></script>
<script type="text/javascript" src="getValue.js" charset="utf-8"></script>
</head>
<body>
Enter Value <input id="name" type="text"/><br><br>
<button onclick="myFunction()">Submit</button>
<br>
<br>
<p id="demo"></p>
</body>
</html>
ViewController -
import UIKit
import WebKit
class ViewController: UIViewController, WKScriptMessageHandler,UITextFieldDelegate {
@IBOutlet weak var webValueLabel: UILabel!
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var toWebTextField: UITextField!
var bool: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
toWebTextField.delegate = self
let URL = Bundle.main.url(forResource: "webPage", withExtension: "html")
let requestObj = NSURLRequest(url: URL!)
webView.load(requestObj as URLRequest)
webView.configuration.userContentController.add(self,name: "scriptHandler")
webView.configuration.userContentController.add(self, name: "reciever")
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if (bool){
let hello = toWebTextField.text!
webView.evaluateJavaScript("display('\(hello)')",
completionHandler: nil)
}
textField.resignFirstResponder()
return true
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if(message.name == "scriptHandler") {
print("JavaScript is sending a message \(message.body)")
webValueLabel.text = message.body as? String
}
if(message.name == "reciever") {
bool = message.body as! Bool
}
}
}
extension ViewController {
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.view.endEditing(true)
}
}