在本机Safari应用程序扩展中,如何从swift中调用带有argumemts的javascript函数?

时间:2019-02-20 11:09:02

标签: javascript ios swift

我只想从safari应用程序扩展中的swift文件中调用一个javascript函数,所以我联系了很多。 我是新手,我不知道该怎么做。请帮帮我:

import SafariServices
import JavaScriptCore
import WebKit
class SafariExtensionHandler: SFSafariExtensionHandler,WKNavigationDelegate {

    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").

        SFSafariApplication.getActiveWindow { (window) in
            window?.getActiveTab { (tab) in
                tab?.getActivePage(completionHandler: { (page1) in
                    page1?.webFrame.javaScriptContext.evaluateScript("myFunction('123')");
                })
            }
        }
    }
}

我遇到错误:

  

[SFSafariPage webFrame]:无法识别的选择器已发送到实例

1 个答案:

答案 0 :(得分:2)

我认为Apple documentation中描述的方式是使用主类(即SafariExtensionHandler类)在文件中调用dispatchMessageToScript函数,并在javascript文件上设置侦听器以侦听以下消息:并根据消息采取行动。

因此,具有您的主类(在我的情况下为SafariExtensionHandler.swift)的文件看起来像这样。

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").
        if messageName == "GetWebsiteUrl" {
            page.dispatchMessageToScript(withName: "WebsiteUrl")
        }
    }
}

您要注入的javascript文件看起来像这样。

// Wait for the DOM to load before dispatching a message to the app extension's Swift code.
document.addEventListener("DOMContentLoaded", function(event) {
    safari.extension.dispatchMessage("GetWebsiteUrl");
});

// Listens for messages sent from the app extension's Swift code.
safari.self.addEventListener("message", messageHandler);

function messageHandler(event) {
    if(event.name === "WebsiteUrl"){
        console.log("WebsiteUrl >>>", document.URL)
    }
}