ipc-protocol.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 {
  12. cmd,
  13. callback,
  14. error,
  15. payload,
  16. options
  17. } = message
  18. // use custom protocol for IPC if:
  19. // - the flag is set to true or
  20. // - the command is the fetch data command or
  21. // - when not on Linux/Android
  22. // AND
  23. // - when not on macOS with an https URL
  24. if (
  25. (
  26. useCustomProtocol ||
  27. cmd === fetchChannelDataCommand ||
  28. !(osName === 'linux' || osName === 'android')
  29. ) &&
  30. !(osName === 'macos' && location.protocol === 'https:')
  31. ) {
  32. console.log('process')
  33. const {
  34. contentType,
  35. data
  36. } = processIpcMessage(payload)
  37. fetch(window.__TAURI__.convertFileSrc(cmd, 'ipc'), {
  38. method: 'POST',
  39. body: data,
  40. headers: {
  41. 'Content-Type': contentType,
  42. 'Tauri-Callback': callback,
  43. 'Tauri-Error': error,
  44. ...options?.headers
  45. }
  46. }).then((response) => {
  47. const cb = response.ok ? callback : error
  48. // we need to split here because on Android the content-type gets duplicated
  49. switch ((response.headers.get('content-type') || '').split(',')[0]) {
  50. case 'application/json':
  51. return response.json().then((r) => [cb, r])
  52. case 'text/plain':
  53. return response.text().then((r) => [cb, r])
  54. default:
  55. return response.arrayBuffer().then((r) => [cb, r])
  56. }
  57. }).then(([cb, data]) => {
  58. if (window[`_${cb}`]) {
  59. window[`_${cb}`](data)
  60. } else {
  61. 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.`)
  62. }
  63. })
  64. } else {
  65. // otherwise use the postMessage interface
  66. const {
  67. data
  68. } = processIpcMessage({
  69. cmd,
  70. callback,
  71. error,
  72. options,
  73. payload
  74. })
  75. window.ipc.postMessage(data)
  76. }
  77. }
  78. })
  79. })()