swift2 使用Swift在iOS WKWebview中捕捉Javascript事件

zazmityj  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(234)

我正在用网络编程语言构建一个应用程序,希望在用户点击HTML按钮时启动摄像头。由于我希望我的摄像头视图是自定义的,所以我需要用Swift来设计它。所以当用户点击这个HTML按钮时,我希望在Swift中“捕捉”这个点击,这样我就可以启动我的原生摄像头视图。
我知道这可以用WKWebview来完成,但我真的不知道该怎么做。
例如,我的Javascript(jQuery)代码可能如下所示:

// User clicks to start the native camera with Swift
$(".camera_button").click(function() {
    // Function to call the camera view from JS to Swift
});

你能帮我做那件事吗?

  • 谢谢-谢谢
eaf3rand

eaf3rand1#

首先,设置html字符串:

var playerURL = """"
    https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/\(trackId)%3Fsecret_token%3D\(secretToken)&auto_play=false&hide_related=true&show_comments=false&show_user=false&show_reposts=false&show_teaser=false&visual=false
"""

其次,创建WKWebView并对其进行配置

private var webView: WKWebView?

override func awakeFromNib() {
    super.awakeFromNib()

    ...(1)...

    self.webView?.navigationDelegate = self
    self.webView?.isUserInteractionEnabled = true
    self.webView?.scrollView.isScrollEnabled = false
    self.webView?.allowsLinkPreview  = false
    self.webView?.contentMode = .scaleAspectFit
    self.webView?.loadHTMLString(self.playerUrl, baseURL: nil)

    DispatchQueue.main.async {
        self.webView = WKWebView(frame: self.viewSoundclound.bounds, configuration: config)
        guard let webView = self.webView else { return }
        self.viewSoundclound.addSubview(webView)
    }
}

第三,设置要添加到WKWebViewJavasScript脚本的配置

override func awakeFromNib() {
    super.awakeFromNib()
    let config = WKWebViewConfiguration()
    let script = WKUserScript(source: self.eventListenerScript, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
    config.userContentController.addUserScript(script)
    config.userContentController.add(self, name: "soundCloundEvents")

    ...(2)...
}

之后,创建您的脚本。重要:“messageHandler.(name).postMessage”中名称必须等于此行中的名称:

'config.userContentController.add(self, name: "soundCloundEvents")'

private var eventListenerScript = """
    var iframe = document.querySelector('iframe');
    widget = SC.Widget(iframe);
    widget.bind(SC.Widget.Events.PLAY, function() {
        window.webkit.messageHandlers.soundCloundEvents.postMessage('PLAY');
    });
    widget.bind(SC.Widget.Events.FINISH, function() {
        window.webkit.messageHandlers.soundCloundEvents.postMessage('FINISH');
    });
"""

最后,扩展Controller或Cell(本例)以侦听脚本

extension PodcastsListTableViewCell: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print(message)
   }
}
ldfqzlk8

ldfqzlk82#

根据@亚历克斯·佩尔蒂埃的回答,这对我很有帮助,下面是我的问题的解决方案。
在我的“loadView()”函数中,我有以下内容:

let contentController = WKUserContentController();
contentController.addScriptMessageHandler(
    self,
    name: "callbackHandler"
)

let config = WKWebViewConfiguration()
config.userContentController = contentController

webView = WKWebView(frame: CGRectZero, configuration: config)
webView.navigationDelegate = self
view = webView

我的函数处理发送到Swift的Javascript事件:

func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
    {
        if(message.name == "callbackHandler") {
            print("Launch my Native Camera")
        }
    }

......最后,我的Javascript(jQuery)代码,当点击我的相机按钮时(HTML格式):

$(document).ready(function() {

    function callNativeApp () {
        try {
            webkit.messageHandlers.callbackHandler.postMessage("camera");
        } catch(err) {
            console.log('The native context does not exist yet');
        }
    }

    $(".menu-camera-icon").click(function() {
        callNativeApp();
    });
});

我希望它能帮助其他人:-)!

wwodge7n

wwodge7n3#

首先我们创建一个js文件。在js中,当你点击一个元素时,你可以发送一条消息,如下所示:

varmessageToPost = {'ButtonId':'clickMeButton'};
window.webkit.messageHandlers.buttonClicked.postMessage(messageToPost);

创建js文件和wkwebview之后,需要注入脚本:

// Setup WKUserContentController instance for injecting user script
  var userController:WKUserContentController= WKUserContentController()

  // Get script that's to be injected into the document
  let js:String= GetScriptFromResources()

  // Specify when and where and what user script needs to be injected into the web document
  var userScript:WKUserScript =  WKUserScript(source: js,
                                         injectionTime: WKUserScriptInjectionTime.AtDocumentEnd
                                         forMainFrameOnly: false)

  // Add the user script to the WKUserContentController instance
  userController.addUserScript(userScript)

  // Configure the WKWebViewConfiguration instance with the WKUserContentController
  webCfg.userContentController= userController;

  //set the message handler
  userController.addScriptMessageHandler(self, name: "buttonClicked")

最后你必须添加监听器函数:

func userContentController(userContentController: WKUserContentController,
                           didReceiveScriptMessage message: WKScriptMessage) {

        if let messageBody:NSDictionary= message.body as? NSDictionary{
            // Do stuff with messageBody
        }

    }

Source Code

相关问题