Skip to content

Commit

Permalink
Gloo net fetch in worker (#253)
Browse files Browse the repository at this point in the history
* Enable gloo-net to use fetch in a worker

* Fix(gloo-net): Add missing web-sys feature DedicatedWorkerGlobalScope

* feat(gloo-net): Use WorkerGlobalScope to support usage in web extensions with manifest V3

Co-authored-by: Chris Joel <0xcda7a@gmail.com>
  • Loading branch information
flosse and cdata committed Nov 4, 2022
1 parent 7736cf1 commit b8f969f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions crates/net/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ http = [
'web-sys/ReadableStream',
'web-sys/Blob',
'web-sys/FormData',
'web-sys/WorkerGlobalScope',
]
# Enables the EventSource API
eventsource = [
Expand Down
3 changes: 3 additions & 0 deletions crates/net/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ pub enum Error {
#[from]
serde_json::Error,
),
/// Error returned by this crate
#[error("{0}")]
GlooError(String),
}

#[cfg(any(feature = "http", feature = "websocket", feature = "eventsource"))]
Expand Down
19 changes: 18 additions & 1 deletion crates/net/src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mod headers;
mod query;

use crate::{js_to_error, Error};
use js_sys::Reflect;
use js_sys::{ArrayBuffer, Uint8Array};
use std::fmt;
use wasm_bindgen::prelude::*;
Expand Down Expand Up @@ -252,7 +253,23 @@ impl Request {
let request =
web_sys::Request::new_with_str_and_init(&url, &self.options).map_err(js_to_error)?;

let promise = gloo_utils::window().fetch_with_request(&request);
let global = js_sys::global();
let maybe_window =
Reflect::get(&global, &JsValue::from_str("Window")).map_err(js_to_error)?;
let promise = if !maybe_window.is_undefined() {
let window = global.dyn_into::<web_sys::Window>().unwrap();
window.fetch_with_request(&request)
} else {
let maybe_worker = Reflect::get(&global, &JsValue::from_str("WorkerGlobalScope"))
.map_err(js_to_error)?;
if !maybe_worker.is_undefined() {
let worker = global.dyn_into::<web_sys::WorkerGlobalScope>().unwrap();
worker.fetch_with_request(&request)
} else {
panic!("Unsupported JavaScript global context");
}
};

let response = JsFuture::from(promise).await.map_err(js_to_error)?;
match response.dyn_into::<web_sys::Response>() {
Ok(response) => Ok(Response {
Expand Down

0 comments on commit b8f969f

Please sign in to comment.