[英]how to communicate between safari app and html page loaded from safari app extension resources folder
[英]Safari App Extensions: Load HTML file on HTTPS page
我正在開發 Safari 應用程序擴展(因為 Safari 擴展現已正式棄用),我想通過 JS 將一些 HTML 注入頁面。 但是,當我向safari-extension://
URL 發出請求時,該請求是在沒有 SSL 的情況下發出的,而 Safari 當前會阻止混合內容,並且不允許以任何方式更改該策略。 所以我有兩個問題。
我怎樣才能為我的開發環境解決這個問題?
我在這里的評論中讀到生產打包擴展(舊的 Safari 擴展)將使用 SSL 加載資源。 Safari App Extensions 是這樣嗎?
編輯
我有一個 Apple Developer 帳戶,簽署了我的擴展程序,但仍然沒有運氣。
我使用 safari 向 Safari App Extension 公開的消息傳遞協議將 HTML 作為字符串發送到響應中。
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 進程,並且在發送多條消息時,響應可能會亂序返回。
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")
}
}
}
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.