handle messages coming from scripts to app

This commit is contained in:
Kyle Spearrin 2019-08-16 08:43:38 -04:00
parent af77175616
commit 07f594a7fd
3 changed files with 36 additions and 5 deletions

View File

@ -12,11 +12,19 @@ class SafariExtensionHandler: SFSafariExtensionHandler {
override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) {
// This method will be called when a content script provided by your extension calls safari.extension.dispatchMessage("message").
page.getPropertiesWithCompletionHandler { properties in
NSLog("The extension received a message (\(messageName)) from a script injected into (\(String(describing: properties?.url))) with userInfo (\(userInfo ?? [:]))")
if(messageName == "bitwarden") {
page.getPropertiesWithCompletionHandler { properties in
NSLog("The extension received a message (\(messageName)) from a script injected into (\(String(describing: properties?.url))) with userInfo (\(userInfo ?? [:]))")
DispatchQueue.main.async {
SafariExtensionViewController.shared.replyMessageFromScript(msg: userInfo)
}
}
}
page.dispatchMessageToScript(withName: "getInfo", userInfo: ["hello": "world", "foo": "bar"])
// page.dispatchMessageToScript(withName: "getInfo", userInfo: ["hello": "world", "foo": "bar"])
}
override func toolbarItemClicked(in window: SFSafariWindow) {

View File

@ -90,10 +90,27 @@ class SafariExtensionViewController: SFSafariExtensionViewController, WKScriptMe
}
func replyMessage(message: AppMessage) {
if(webView == nil) {
return;
}
let json = (jsonSerialize(obj: message) ?? "null")
webView.evaluateJavaScript("window.bitwardenSafariAppMessageReceiver(\(json));", completionHandler: nil)
}
func replyMessageFromScript(msg: [String : Any]?) {
if(webView == nil) {
return;
}
let newMsg = AppMessage()
newMsg.command = "cs_message"
do {
let jsonData = try JSONSerialization.data(withJSONObject: msg as Any, options: [])
newMsg.data = String(data: jsonData, encoding: .utf8)
} catch let error {
print("error converting to json: \(error)")
}
replyMessage(message: newMsg)
}
}
func jsonSerialize<T: Encodable>(obj: T?) -> String? {
@ -120,6 +137,12 @@ func jsonDeserialize<T: Decodable>(json: String?) -> T? {
}
class AppMessage : Decodable, Encodable {
init() {
id = ""
command = ""
data = nil
responseData = nil
}
var id: String
var command: String
var data: String?

View File

@ -1,5 +1,5 @@
document.addEventListener("DOMContentLoaded", (event) => {
safari.extension.dispatchMessage("Hello World!", { key: "value2" });
safari.extension.dispatchMessage("bitwarden", { hello: "world!!!" });
safari.self.addEventListener("message", (e) => {
console.log(e);