我如何从 SafariExtensionHandler 向页面上的注入脚本发送消息

How i can send message to the Injected Script on page from SafariExtensionHandler

我可以在 override func messageReceived 中使用 from page 属性和 dispatchMessageToScript 方法在收到消息时发送消息,但我不明白在 injectOpenWelcomeTab 中我该怎么做方法。谢谢

import SafariServices

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 ?? [:]))")

            //Вот таким образом можем дёргать методы из контроллера
            SafariExtensionViewController.shared.popupChangeBackgorundColor()           
        }

        page.dispatchMessageToScript(withName: "openWelcomePage")
    }

    public func injectOpenWelcomeTab(){           
        //Here I want send message to injected script        
    }     
}

SFSafariApplication.getActiveWindow 是你最好的朋友。 只要确保你 import SafariServices

func injectOpenWelcomeTab() {
    getActivePage {
        [=10=]?.dispatchMessageToScript(withName: "openWelcomePage", userInfo: ["foo": bar as Any])
    }
}

func getActivePage(completionHandler: @escaping (SFSafariPage?) -> Void) {
    SFSafariApplication.getActiveWindow {[=10=]?.getActiveTab {[=10=]?.getActivePage(completionHandler: completionHandler)}}
}