Search code examples
swiftmacossafari-app-extension

Why property of type SFSafariPage become nil?


The SFSafariPage property get it value like this

class SafariExtensionHandler: SFSafariExtensionHandler {

var somePage: SFSafariPage?

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").
    if messageName == "script injected successfully" {
        somePage = page
        NSLog(String(describing: somePage))
    }
}

but when i try to use it

func performPlayerAction(_ action: PlayerAction) {
    NSLog("page %@", String(describing: somePage))
    somePage?.dispatchMessageToScript(withName: action.rawValue, userInfo: nil)
}

the value of property somePage is nil. Why this happed? Thanks a lot!


Solution

  • If content script is sending a message to extension handler, the message will trigger the method messageReceived where we can process the data. For each message there will be a new instance of the extension handler, so we cannot share information between the extension handlers unless we make your variables static.

    The solution is:

        static var somePage: SFSafariPage?