簡體   English   中英

為什么 SFSafariPage 類型的屬性變為 nil?

[英]Why property of type SFSafariPage become nil?

SFSafariPage 屬性像這樣獲取它的值

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))
    }
}

但是當我嘗試使用它時

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

屬性 somePage 的值為 nil。 為什么會這樣? 非常感謝!

如果內容腳本正在向擴展處理程序發送消息,該消息將觸發方法messageReceived ,我們可以在其中處理數據。 對於每條消息,都會有一個擴展處理程序的新實例,因此我們不能在擴展處理程序之間共享信息,除非我們將您的變量設為 static。

解決方案是:

    static var somePage: SFSafariPage?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM