ipc-protocol.js 2.6 KB

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