script/dom/
userscripts.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::rc::Rc;
6
7use js::jsval::UndefinedValue;
8use script_bindings::root::DomRoot;
9
10use crate::dom::bindings::str::DOMString;
11use crate::dom::html::htmlheadelement::HTMLHeadElement;
12use crate::dom::html::htmlscriptelement::SourceCode;
13use crate::dom::node::NodeTraits;
14use crate::dom::window::Window;
15use crate::script_module::ScriptFetchOptions;
16use crate::script_runtime::CanGc;
17
18pub(crate) fn load_script(head: &HTMLHeadElement) {
19    let doc = head.owner_document();
20    let userscripts = doc.window().userscripts().to_owned();
21    if userscripts.is_empty() {
22        return;
23    }
24    let win = DomRoot::from_ref(doc.window());
25    doc.add_delayed_task(task!(UserScriptExecute: |win: DomRoot<Window>| {
26        let cx = win.get_cx();
27        rooted!(in(*cx) let mut rval = UndefinedValue());
28
29        for user_script in userscripts {
30            let script_text = SourceCode::Text(
31                Rc::new(DOMString::from_string(user_script.script))
32            );
33            let global_scope = win.as_global_scope();
34            _ = global_scope.evaluate_script_on_global_with_result(
35                &script_text,
36                &user_script.source_file.map(|path| path.to_string_lossy().to_string()).unwrap_or_default(),
37                rval.handle_mut(),
38                1,
39                ScriptFetchOptions::default_classic_script(global_scope),
40                global_scope.api_base_url(),
41                CanGc::note(),
42                None,
43            );
44        }
45    }));
46}