chrome_types/
runtime.rs

1use crate::sys::{CHROME, Chrome};
2use js_sys::{Function, Object};
3use wasm_bindgen::prelude::*;
4
5type OnMessageCallback = Closure<dyn Fn(JsValue, Object, Function) -> bool>;
6type SendResponse<'a> = &'a dyn FnOnce(&JsValue) -> Result<(), JsValue>;
7
8pub fn get_manifest() -> Object {
9  CHROME.with(Chrome::runtime).get_manifest()
10}
11
12pub fn on_message<F>(callback: F)
13where
14  F: Fn(JsValue, Object, SendResponse) -> bool + 'static,
15{
16  let closure = OnMessageCallback::new(move |message: JsValue, sender: Object, f: Function| {
17    callback(message, sender, &move |response: &JsValue| {
18      f.call1(&JsValue::NULL, response).map(drop)
19    })
20  });
21
22  let closure_ref = closure.as_ref().unchecked_ref::<Function>();
23  CHROME
24    .with(Chrome::runtime)
25    .on_message()
26    .add_listener(closure_ref);
27}
28
29pub async fn send_message(message: &JsValue) -> Result<JsValue, JsValue> {
30  CHROME
31    .with(Chrome::runtime)
32    .send_message(None, message, None)
33    .await
34}