Integrating ONLYOFFICE mobile web editors

    Please note that ONLYOFFICE mobile web editors are available only for commercial builds of Enterprise and editions.

    • iOS
    • Android

    In this section, we will look at the integration process via WKWebView using the mobile demo sample for iOS which is available on .

    This example demonstrates how to integrate ONLYOFFICE mobile web editors with the ONLYOFFICE .

    Opening ONLYOFFICE editors

    1. Download and install ONLYOFFICE Docs Enterprise or edition.
    2. Download the mobile demo sample for iOS from GitHub.
    3. Open the EditorWebViewDemo.xcodeproj project with to modify code fragments of this example for your DMS to work correctly.
    4. To display the main page of your DMS, specify the address of the Document Server web interface in the value of the DocumentServerURL property in the Info.plist file:

      where the documentserver is the name of the server with the ONLYOFFICE Document Server installed.

      If DocumentServerURL is specified, the DMS main page is loaded. Otherwise, an error occurs:

      1. if documentServerUrlString.isEmpty {
      2. showAlert(title: "Error", message: "You must specify the document server address, the \"DocumentServerURL\" value in the Info.plist file.")
      3. return
      4. }
      5. guard let url = URL(string: documentServerUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "") else {
      6. return
      7. }
      8. webView.load(URLRequest(url: url))
      9. }

      iOS error

      DocumentServerURL is not specified

      DocumentServerURL is specified

    5. Use the DocumentServerViewController controller to open the editors correctly on iOS devices. In this controller, define a function to open a document via WKWebView component. First, request an absolute URL and check if it contains the “/editor?” string. If so, add an additional query parameter (the mobile platform type) to the link:

      1. private var openDocumentMarker = "/editor?"
      2. private var additionalQueryParameters = ["type": "mobile"]
      3. func webView(_ webView: WKWebView,
      4. decidePolicyFor navigationAction:
      5. WKNavigationAction,
      6. decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
      7. {
      8. guard let urlString = navigationAction.request.url?.absoluteString else {
      9. decisionHandler(.cancel)
      10. return
      11. }
      12. if urlString.contains(openDocumentMarker),
      13. let redirectUrl = navigationAction.request.url?.appendingQueryParameters(additionalQueryParameters)
      14. {
      15. decisionHandler(.cancel)
      16. navigator.navigate(to: .documentServerEditor(url: redirectUrl))
      17. } else {
      18. reloadItem.isEnabled = true
      19. backItem.isEnabled = webView.canGoBack
      20. forwardItem.isEnabled = webView.canGoForward
      21. title = navigationAction.request.url?.host ?? ""
      22. decisionHandler(.allow)
      23. }
      24. }
    6. In the DocumentServerViewController controller, create the navigation actions available on the DMS main page. For example, in our test sample, they are specified with the interface elements such as the Reload, Back, and Forward buttons.

    7. For easy interaction with the editor, define the Activity Indicator and Progress View UI components.

      The full code for DocumentServerViewController can be found here.

      Activity indicator

      Activity Indicator

      Progress View

      Buttons

      Buttons

      1. private func configureView() {
      2. let preferences = WKPreferences()
      3. let configuration = WKWebViewConfiguration()
      4. preferences.javaScriptEnabled = true
      5. configuration.preferences = preferences
      6. webView = WKWebView(frame: .zero, configuration: configuration)
      7. view.addSubview(webView)
      8. webView.translatesAutoresizingMaskIntoConstraints = false
      9. webView.navigationDelegate = self
      10. webView.uiDelegate = self
      11. if let webViewSuperview = webView.superview {
      12. webView.topAnchor.constraint(equalTo: webViewSuperview.topAnchor).isActive = true
      13. webView.leadingAnchor.constraint(equalTo: webViewSuperview.leadingAnchor).isActive = true
      14. webView.bottomAnchor.constraint(equalTo: webViewSuperview.bottomAnchor).isActive = true
      15. webView.trailingAnchor.constraint(equalTo: webViewSuperview.trailingAnchor).isActive = true
      16. }
      17. ...
      18. }
    8. In the Xcode toolbar, select a build scheme and a device where the app will be run. After that, choose Product -> Run, or click the Run button in the project toolbar to build and run your code.

    9. On the main screen of the application, select the Using DocumentServer option to demonstrate an example of integrating ONLYOFFICE mobile web editors with the ONLYOFFICE test or DMS sample.

    Closing ONLYOFFICE editors

    Use the DocumentServerEditorViewController controller to exit from the editor. For example, in the current test samples the Go back button is created to navigate to the previous screen:

    1. private let goBackUrl = Bundle.main.object(forInfoDictionaryKey: "DocumentServerURL") as? String ?? ""
    2. func webView(_ webView: WKWebView,
    3. decidePolicyFor navigationAction: WKNavigationAction,
    4. decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
    5. {
    6. decisionHandler(.cancel)
    7. return
    8. }
    9. if urlString == goBackUrl {
    10. decisionHandler(.cancel)
    11. navigationController?.popViewController(animated: true)
    12. } else {
    13. decisionHandler(.allow)
    14. }
    15. }

    Button to exit the editor

    The full code for DocumentServerEditorViewController can be found .

    This example demonstrates how to open the ONLYOFFICE editors via WKWebView using the editor configuration described in the and the configuration examples.

    iOS integration via api

    Opening ONLYOFFICE editors

    1. Download and install ONLYOFFICE Docs or Developer edition.
    2. Download the mobile demo sample for iOS from .
    3. Open the EditorWebViewDemo.xcodeproj project with Xcode to modify code fragments of this example for your DMS to work correctly.
    4. Create an empty html file. The demo project resource is used as a template.

    5. Add the div element as shown below:

      1. <div id="placeholder"></div>
    6. Specify your ONLYOFFICE Document Server link with the JavaScript API that will be used for your website:

      where the documentserver is the name of the server with the ONLYOFFICE Document Server installed.

    7. Add the script initializing the Document Editor for the div element with the configuration for the document you want to open:

      1. window.docEditor = new DocsAPI.DocEditor("placeholder",
      2. {
      3. {external_config},
      4. "type": "mobile",
      5. "events": {
      6. "onAppReady": onAppReady,
      7. "onDocumentReady": onDocumentReady,
      8. "onDownloadAs": onDownloadAs,
      9. "onError": onError,
      10. "onInfo": onInfo,
      11. "onRequestClose": onRequestClose,
      12. "onRequestInsertImage": onRequestInsertImage,
      13. "onRequestUsers": onRequestUsers,
      14. "onWarning": onWarning,
      15. }
      16. });
    8. To start working with documents, display the ONLYOFFICE editor on your mobile device via the WKWebView component. To do this, specify the EditorViewController controller. Request the URL to the editor.html file, get its contents and replace the “{external_config}” parameter with a config from the samples.plist file where all the sample configurations are categorized according to API documentation Try page:

      1. private func load() {
      2. guard let url = Bundle.main.url(forResource: "editor", withExtension: "html") else {
      3. return
      4. }
      5. var html = ""
      6. do {
      7. html = try String(contentsOf: url)
      8. } catch {
      9. print(error)
      10. }
      11. html = html.replacingOccurrences(of: "{external_config}", with: config ?? "")
      12. webView.loadHTMLString(html, baseURL: nil)
      13. }

      ONLYOFFICE Editor Samples

      The full code for EditorViewController can be found .

    9. In the Xcode toolbar, select a build scheme and a device where the app will be run. After that, choose Product -> Run, or click the Run button in the project toolbar to build and run your code.

    10. On the main screen of the application, select the Using API Configuration option to demonstrate how to open the ONLYOFFICE mobile web editors using the editor configuration described in the API documentation and the configuration examples.
    11. On the next page, choose one of the configuration samples to open the resulting HTML in the WKWebView component.

    Working with documents

    To work with documents (open, download, insert images, mention other users, etc.), use the API documentation with its events and methods:

    1. To track events and call appropriate methods, handle the events of ONLYOFFICE editors in native code by the EditorEventsHandler controller and then delegate them to EditorViewController:

      1. var delegate: EditorEventsDelegate?
      2. convenience init(configuration: WKWebViewConfiguration) {
      3. self.init()
      4. configuration.userContentController.add(self, name: EditorEvent.onDownloadAs.rawValue)
      5. ....
      6. }
      7. extension EditorEventsHandler: WKScriptMessageHandler {
      8. func userContentController(_ userContentController: WKUserContentController,
      9. didReceive message: WKScriptMessage)
      10. {
      11. let event = EditorEvent(rawValue: message.name)
      12. switch event {
      13. case .onDownloadAs:
      14. guard
      15. let json = message.body as? [String: Any],
      16. let fileType = json["fileType"] as? String,
      17. let url = json["url"] as? String
      18. else { return }
      19. delegate?.onDownloadAs(fileType: fileType, url: url)
      20. ...
      21. }
      22. }
      23. }
      1. print("⚡ ONLYOFFICE Document Editor create file: \(url)")
      2. }
    2. Define the callMethod function to call from native code. It can take string, boolean or object values as arguments. This function adds the method name and its arguments to the string with the JavaScript code and then evaluates JavaScript in the WKWebView component with the evaluateJavaScript method:

      1. private func callMethod(function: String, arg: Bool) {
      2. webView.evaluateJavaScript(javascript, completionHandler: nil)
      3. }
      4. private func callMethod(function: String, arg: String) {
      5. let javascript = "window.docEditor.\(function)(\"\(arg)\")"
      6. webView.evaluateJavaScript(javascript, completionHandler: nil)
      7. }
      8. private func callMethod(function: String, arg: [String: Any]) {
      9. guard
      10. let json = try? JSONSerialization.data(withJSONObject: arg, options: []),
      11. let jsonString = String(data: json, encoding: .utf8)
      12. else {
      13. return
      14. }
      15. let javascript = "window.docEditor.\(function)(\(jsonString))"
      16. webView.evaluateJavaScript(javascript, completionHandler: nil)
      17. }

      The full code for EditorEventsHandler can be found here.

    3. To display the result of downloading and printing a document, use the PreviewController controller. This controller is based on QLPreviewController. Download a document by its URL and set the dataSource and delegate properties to QLPreviewController:

      The full code for PreviewController can be found .

    In this section, we will look at the integration process via WebView using the mobile demo sample for Android which is available on .

    This example demonstrates how to integrate ONLYOFFICE mobile web editors with the ONLYOFFICE .

    Android integration via test sample

    Opening ONLYOFFICE editors

    1. Download and install ONLYOFFICE Docs Enterprise or edition.
    2. Download the mobile demo sample for Android from GitHub.
    3. Open the top-level build.gradle file with to modify code fragments of this example for your DMS to work correctly.
    4. To display the main page of your DMS, specify the address of the Document Server web interface in the value of the DOCUMENT_SERVER_URL property in the module-level build.gradle file:

      1. buildConfigField("String", "DOCUMENT_SERVER_URL", "https://documentserver/")

      where the documentserver is the name of the server with the ONLYOFFICE Document Server installed.

      If DOCUMENT_SERVER_URL is specified, the DMS main page is loaded. Otherwise, an error occurs:

      1. private fun showDialog() {
      2. AlertDialog.Builder(requireContext())
      3. .setMessage("Document server url is empty.\nYou must specify the address in build.gradle")
      4. .setPositiveButton("Ok") { dialog, _ ->
      5. dialog.dismiss()
      6. requireActivity().finish()
      7. }
      8. .create()
      9. .show()
      10. }

      DocumentServerURL is not specified

      Android managing

      DocumentServerURL is specified

    5. Use the MainFragment.kt controller to open the editors correctly on Android devices. In this controller, define a function to open a document via WebView component. Request a URL and check if it contains the “editor” string which specifies that the document will be opened:

      1. private class MainWebViewClient(private val navController: NavController) : WebViewClient() {
      2. override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
      3. val url = request?.url
      4. if (url != null) {
      5. val path = url.path
      6. if (path?.contains("editor") == true) {
      7. navController.navigate(R.id.action_mainFragment_to_editorFragment, Bundle(1).apply {
      8. putString("document_url", url.toString())
      9. })
      10. return true
      11. }
      12. return false
      13. }
      14. return super.shouldOverrideUrlLoading(view, request)
      15. }
      16. }

      The full code for MainFragment.kt can be found here.

    6. To start working with documents, display the ONLYOFFICE editor on your mobile device via the WebView component. To do this, set up WebView and layout in the EditorFragment.kt controller as follows:

      1. @SuppressLint("SetJavaScriptEnabled")
      2. private fun setSettings() {
      3. webView?.settings?.apply {
      4. javaScriptEnabled = true
      5. javaScriptCanOpenWindowsAutomatically = true
      6. loadWithOverviewMode = true
      7. cacheMode = WebSettings.LOAD_NO_CACHE
      8. domStorageEnabled = true
      9. }
      10. webView?.webViewClient = EditorWebViewClient(findNavController())
      11. }
    7. In the Android Studio toolbar, select your application and the device where the app will be run. After that, click the Run button in the project toolbar to build and run your code.

    8. The application will be opened to demonstrate an example of integrating ONLYOFFICE mobile web editors with the ONLYOFFICE test or DMS sample.

    Closing ONLYOFFICE editors

    Use the EditorFragment.kt controller to exit from the editor:

    1. private class EditorWebViewClient(private val navController: NavController) : WebViewClient() {
    2. override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
    3. request?.url?.let { url ->
    4. if (!url.toString().contains("editor")) {
    5. navController.popBackStack()
    6. return true
    7. }
    8. }
    9. return super.shouldOverrideUrlLoading(view, request)
    10. }
    11. }

    The full code for EditorFragment.kt can be found .