我使用 safari 向 Safari App Extension 公开的消息传递协议将 HTML 作为字符串发送到响应中。
内容脚本请求 HTML 模板 (JS)
let sendMessage = (msgObj, callback) => {
msgObj.callbackIndex = (safariCallbackCount++).toString();
let callbackKey = msgObj['type']+'_'+msgObj.callbackIndex;
if (typeof callback === 'function')
messageCallbacks[callbackKey] = callback;
safari.extension.dispatchMessage(msgObj['type'], msgObj);
}
sendMessage({type: 'loadTemplate', path: path}, callback );
请注意存储回调函数的messageCallbacks散列以及用于索引唯一性的计数器。您正在将消息传递给 Swift 进程,并且在发送多条消息时响应可能会乱序返回。
SFSafariExtensionHandler 监听消息和句柄(swift)
func loadTemplate (withPage page: SFSafariPage, withUrl url: URL, withCallbackIndex callbackIndex: String) {
let pathExtention = url.pathExtension
let pathPrefix = url.path.replacingOccurrences(of: "." + pathExtention, with: "", options: .literal, range: nil)
if let filepath = Bundle.main.path(forResource: pathPrefix, ofType: pathExtention) {
do {
let contents = try String(contentsOfFile: filepath, encoding: .utf8)
page.dispatchMessageToScript(withName: "loadTemplate", userInfo: ["htmlData": contents, "callbackIndex": callbackIndex])
} catch {
// contents could not be loaded
NSLog("ERROR CONTENTS COULD NOT BE LOADED FROM \(filepath)")
}
} else {
NSLog("Could not build file path")
}
}
// This method will be called when a content script provided by your extension calls safari.extension.dispatchMessage("message").
override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) {
page.getPropertiesWithCompletionHandler { properties in
switch messageName {
case "loadTemplate":
self.loadTemplate(withPage: page, withUrl: URL(string: userInfo?["path"] as! String)!, withCallbackIndex: userInfo?["callbackIndex"] as! String)
default:
NSLog("NO DEFINITION FOR STRING VALUE")
}
}
}
内容脚本处理响应 (JS)
let handleMessage = event => {
let callbackIndex = event.message.callbackIndex;
delete event.message.callbackIndex;
let callbackKey = event.name+'_'+callbackIndex;
if ( typeof messageCallbacks[callbackKey] === 'function' ) {
messageCallbacks[callbackKey](event.message);
delete messageCallbacks[callbackKey]
}
};
safari.self.addEventListener("message", handleMessage);
//// html data is accessible from event.message.htmlData