ipc-protocol.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. ;(function () {
  5. const processIpcMessage = __RAW_process_ipc_message_fn__
  6. const osName = __TEMPLATE_os_name__
  7. const fetchChannelDataCommand = __TEMPLATE_fetch_channel_data_command__
  8. const useCustomProtocol = __TEMPLATE_use_custom_protocol__
  9. Object.defineProperty(window, '__TAURI_POST_MESSAGE__', {
  10. value: (message) => {
  11. const { cmd, callback, error, payload, options } = message
  12. // use custom protocol for IPC if the flag is set to true, the command is the fetch data command or when not on Linux/Android
  13. if (useCustomProtocol || cmd === fetchChannelDataCommand || (osName !== 'linux' && osName !== 'android')) {
  14. const { contentType, data } = processIpcMessage(payload)
  15. fetch(window.__TAURI__.convertFileSrc(cmd, 'ipc'), {
  16. method: 'POST',
  17. body: data,
  18. headers: {
  19. 'Content-Type': contentType,
  20. 'Tauri-Callback': callback,
  21. 'Tauri-Error': error,
  22. ...options?.headers
  23. }
  24. }).then((response) => {
  25. const cb = response.ok ? callback : error
  26. // we need to split here because on Android the content-type gets duplicated
  27. switch ((response.headers.get('content-type') || '').split(',')[0]) {
  28. case 'application/json':
  29. return response.json().then((r) => [cb, r])
  30. case 'text/plain':
  31. return response.text().then((r) => [cb, r])
  32. default:
  33. return response.arrayBuffer().then((r) => [cb, r])
  34. }
  35. }).then(([cb, data]) => {
  36. if (window[`_${cb}`]) {
  37. window[`_${cb}`](data)
  38. } else {
  39. console.warn(`[TAURI] Couldn't find callback id {cb} in window. This might happen when the app is reloaded while Rust is running an asynchronous operation.`)
  40. }
  41. })
  42. } else {
  43. // otherwise use the postMessage interface
  44. const { data } = processIpcMessage({ cmd, callback, error, options, payload })
  45. window.ipc.postMessage(data)
  46. }
  47. }
  48. })
  49. })()