From 80c12ead4655af91f08046f19c2d478a4cbf94cd Mon Sep 17 00:00:00 2001 From: Lucas Fernandes Nogueira Date: Thu, 7 Mar 2024 14:53:49 -0300 Subject: [PATCH] fix(ipc): wrong response format when using a channel (#9121) --- .changes/fix-channel-ipc-response.md | 5 +++++ core/tauri/src/ipc/channel.rs | 29 ++++++++++++++++++++++------ 2 files changed, 28 insertions(+), 6 deletions(-) create mode 100644 .changes/fix-channel-ipc-response.md diff --git a/.changes/fix-channel-ipc-response.md b/.changes/fix-channel-ipc-response.md new file mode 100644 index 000000000..1ab50f088 --- /dev/null +++ b/.changes/fix-channel-ipc-response.md @@ -0,0 +1,5 @@ +--- +"tauri": patch:bug +--- + +Fix regression on IPC response when using a channel to return objects. diff --git a/core/tauri/src/ipc/channel.rs b/core/tauri/src/ipc/channel.rs index 975e04aa4..609039eb5 100644 --- a/core/tauri/src/ipc/channel.rs +++ b/core/tauri/src/ipc/channel.rs @@ -89,7 +89,28 @@ impl FromStr for JavaScriptChannelId { impl JavaScriptChannelId { /// Gets a [`Channel`] for this channel ID on the given [`Webview`]. pub fn channel_on(&self, webview: Webview) -> Channel { - Channel::from_callback_fn(webview, self.0) + let callback_id = self.0; + let counter = AtomicUsize::new(0); + + Channel::new_with_id(callback_id.0, move |body| { + let data_id = CHANNEL_DATA_COUNTER.fetch_add(1, Ordering::Relaxed); + + webview + .state::() + .0 + .lock() + .unwrap() + .insert(data_id, body); + + let i = counter.fetch_add(1, Ordering::Relaxed); + + webview.eval(&format!( + "window.__TAURI_INTERNALS__.invoke('{FETCH_CHANNEL_DATA_COMMAND}', null, {{ headers: {{ '{CHANNEL_ID_HEADER_NAME}': '{data_id}' }} }}).then((response) => window['_' + {}]({{ message: response, id: {i} }})).catch(console.error)", + callback_id.0 + ))?; + + Ok(()) + }) } } @@ -132,8 +153,6 @@ impl Channel { } pub(crate) fn from_callback_fn(webview: Webview, callback: CallbackFn) -> Self { - let counter = AtomicUsize::new(0); - Channel::new_with_id(callback.0, move |body| { let data_id = CHANNEL_DATA_COUNTER.fetch_add(1, Ordering::Relaxed); @@ -144,10 +163,8 @@ impl Channel { .unwrap() .insert(data_id, body); - let i = counter.fetch_add(1, Ordering::Relaxed); - webview.eval(&format!( - "window.__TAURI_INTERNALS__.invoke('{FETCH_CHANNEL_DATA_COMMAND}', null, {{ headers: {{ '{CHANNEL_ID_HEADER_NAME}': '{data_id}' }} }}).then((response) => window['_' + {}]({{ message: response, id: {i} }})).catch(console.error)", + "window.__TAURI_INTERNALS__.invoke('{FETCH_CHANNEL_DATA_COMMAND}', null, {{ headers: {{ '{CHANNEL_ID_HEADER_NAME}': '{data_id}' }} }}).then((response) => window['_' + {}](response)).catch(console.error)", callback.0 ))?;