Coverage Report

Created: 2026-02-14 08:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.cpp
Line
Count
Source
1
/*
2
 * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
3
 * Copyright (c) 2022, networkException <networkexception@serenityos.org>
4
 *
5
 * SPDX-License-Identifier: BSD-2-Clause
6
 */
7
8
#include <AK/Debug.h>
9
#include <AK/StringBuilder.h>
10
#include <LibTextCodec/Decoder.h>
11
#include <LibWeb/Bindings/HTMLScriptElementPrototype.h>
12
#include <LibWeb/Bindings/Intrinsics.h>
13
#include <LibWeb/DOM/Document.h>
14
#include <LibWeb/DOM/Event.h>
15
#include <LibWeb/DOM/ShadowRoot.h>
16
#include <LibWeb/DOM/Text.h>
17
#include <LibWeb/HTML/EventNames.h>
18
#include <LibWeb/HTML/HTMLScriptElement.h>
19
#include <LibWeb/HTML/Scripting/ClassicScript.h>
20
#include <LibWeb/HTML/Scripting/Fetching.h>
21
#include <LibWeb/HTML/Scripting/ImportMapParseResult.h>
22
#include <LibWeb/HTML/Window.h>
23
#include <LibWeb/Infra/CharacterTypes.h>
24
#include <LibWeb/Infra/Strings.h>
25
#include <LibWeb/MimeSniff/MimeType.h>
26
27
namespace Web::HTML {
28
29
JS_DEFINE_ALLOCATOR(HTMLScriptElement);
30
31
HTMLScriptElement::HTMLScriptElement(DOM::Document& document, DOM::QualifiedName qualified_name)
32
0
    : HTMLElement(document, move(qualified_name))
33
0
{
34
0
}
35
36
0
HTMLScriptElement::~HTMLScriptElement() = default;
37
38
void HTMLScriptElement::initialize(JS::Realm& realm)
39
0
{
40
0
    Base::initialize(realm);
41
0
    WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLScriptElement);
42
0
}
43
44
void HTMLScriptElement::visit_edges(Cell::Visitor& visitor)
45
0
{
46
0
    Base::visit_edges(visitor);
47
0
    if (auto* script = m_result.get_pointer<JS::NonnullGCPtr<Script>>())
48
0
        visitor.visit(*script);
49
0
    visitor.visit(m_parser_document);
50
0
    visitor.visit(m_preparation_time_document);
51
0
}
52
53
void HTMLScriptElement::attribute_changed(FlyString const& name, Optional<String> const& old_value, Optional<String> const& value)
54
0
{
55
0
    Base::attribute_changed(name, old_value, value);
56
57
0
    if (name == HTML::AttributeNames::crossorigin) {
58
0
        m_crossorigin = cors_setting_attribute_from_keyword(value);
59
0
    } else if (name == HTML::AttributeNames::referrerpolicy) {
60
0
        m_referrer_policy = ReferrerPolicy::from_string(value.value_or(""_string)).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString);
61
0
    } else if (name == HTML::AttributeNames::src) {
62
        // https://html.spec.whatwg.org/multipage/scripting.html#script-processing-model
63
        // When a script element el that is not parser-inserted experiences one of the events listed in the following list, the user agent must immediately prepare the script element el:
64
        // - [...]
65
        // - The script element is connected and has a src attribute set where previously the element had no such attribute.
66
0
        if (!is_parser_inserted() && is_connected() && value.has_value() && !old_value.has_value()) {
67
0
            prepare_script();
68
0
        }
69
0
    } else if (name == HTML::AttributeNames::async) {
70
        // https://html.spec.whatwg.org/multipage/scripting.html#script-processing-model:script-force-async
71
        // When an async attribute is added to a script element el, the user agent must set el's force async to false.
72
0
        m_force_async = false;
73
0
    }
74
0
}
75
76
void HTMLScriptElement::begin_delaying_document_load_event(DOM::Document& document)
77
0
{
78
    // https://html.spec.whatwg.org/multipage/scripting.html#concept-script-script
79
    // The user agent must delay the load event of the element's node document until the script is ready.
80
0
    m_document_load_event_delayer.emplace(document);
81
0
}
82
83
// https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block
84
void HTMLScriptElement::execute_script()
85
0
{
86
    // https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-html
87
    // Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for document.
88
0
    if (!m_document->ready_to_run_scripts())
89
0
        main_thread_event_loop().spin_until([&] { return m_document->ready_to_run_scripts(); });
90
91
    // 1. Let document be el's node document.
92
0
    JS::NonnullGCPtr<DOM::Document> document = this->document();
93
94
    // 2. If el's preparation-time document is not equal to document, then return.
95
0
    if (m_preparation_time_document.ptr() != document.ptr()) {
96
0
        dbgln("HTMLScriptElement: Refusing to run script because the preparation time document is not the same as the node document.");
97
0
        return;
98
0
    }
99
100
    // FIXME: 3. Unblock rendering on el.
101
102
    // 3. If el's result is null, then fire an event named error at el, and return.
103
0
    if (m_result.has<ResultState::Null>()) {
104
0
        dbgln("HTMLScriptElement: Refusing to run script because the element's result is null.");
105
0
        dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
106
0
        return;
107
0
    }
108
109
    // 5. If el's from an external file is true, or el's type is "module", then increment document's ignore-destructive-writes counter.
110
0
    bool incremented_destructive_writes_counter = false;
111
0
    if (m_from_an_external_file || m_script_type == ScriptType::Module) {
112
0
        document->increment_ignore_destructive_writes_counter();
113
0
        incremented_destructive_writes_counter = true;
114
0
    }
115
116
    // 5. Switch on el's type:
117
    // -> "classic"
118
0
    if (m_script_type == ScriptType::Classic) {
119
        // 1. Let oldCurrentScript be the value to which document's currentScript object was most recently set.
120
0
        auto old_current_script = document->current_script();
121
        // 2. If el's root is not a shadow root, then set document's currentScript attribute to el. Otherwise, set it to null.
122
0
        if (!is<DOM::ShadowRoot>(root()))
123
0
            document->set_current_script({}, this);
124
0
        else
125
0
            document->set_current_script({}, nullptr);
126
127
0
        if (m_from_an_external_file)
128
0
            dbgln_if(HTML_SCRIPT_DEBUG, "HTMLScriptElement: Running script {}", attribute(HTML::AttributeNames::src).value_or(String {}));
129
0
        else
130
0
            dbgln_if(HTML_SCRIPT_DEBUG, "HTMLScriptElement: Running inline script");
131
132
        // 3. Run the classic script given by el's result.
133
0
        (void)verify_cast<ClassicScript>(*m_result.get<JS::NonnullGCPtr<Script>>()).run();
134
135
        // 4. Set document's currentScript attribute to oldCurrentScript.
136
0
        document->set_current_script({}, old_current_script);
137
0
    }
138
    // -> "module"
139
0
    else if (m_script_type == ScriptType::Module) {
140
        // 1. Assert: document's currentScript attribute is null.
141
0
        VERIFY(document->current_script() == nullptr);
142
143
        // 2. Run the module script given by el's result.
144
0
        (void)verify_cast<JavaScriptModuleScript>(*m_result.get<JS::NonnullGCPtr<Script>>()).run();
145
0
    }
146
    // -> "importmap"
147
0
    else if (m_script_type == ScriptType::ImportMap) {
148
        // 1. Register an import map given el's relevant global object and el's result.
149
0
        m_result.get<JS::NonnullGCPtr<ImportMapParseResult>>()->register_import_map(verify_cast<Window>(relevant_global_object(*this)));
150
0
    }
151
152
    // 7. Decrement the ignore-destructive-writes counter of document, if it was incremented in the earlier step.
153
0
    if (incremented_destructive_writes_counter)
154
0
        document->decrement_ignore_destructive_writes_counter();
155
156
    // 8. If el's from an external file is true, then fire an event named load at el.
157
0
    if (m_from_an_external_file)
158
0
        dispatch_event(DOM::Event::create(realm(), HTML::EventNames::load));
159
0
}
160
161
// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
162
void HTMLScriptElement::prepare_script()
163
0
{
164
    // 1. If el's already started is true, then return.
165
0
    if (m_already_started) {
166
0
        dbgln("HTMLScriptElement: Refusing to run script because it has already started.");
167
0
        return;
168
0
    }
169
170
    // 2. Let parser document be el's parser document.
171
0
    JS::GCPtr<DOM::Document> parser_document = m_parser_document;
172
173
    // 3. Set el's parser document to null.
174
0
    m_parser_document = nullptr;
175
176
    // 4. If parser document is non-null and el does not have an async attribute, then set el's force async to true.
177
0
    if (parser_document && !has_attribute(HTML::AttributeNames::async)) {
178
0
        m_force_async = true;
179
0
    }
180
181
    // 5. Let source text be el's child text content.
182
0
    auto source_text = child_text_content();
183
184
    // 6. If el has no src attribute, and source text is the empty string, then return.
185
0
    if (!has_attribute(HTML::AttributeNames::src) && source_text.is_empty()) {
186
0
        return;
187
0
    }
188
189
    // 7. If el is not connected, then return.
190
0
    if (!is_connected()) {
191
0
        dbgln("HTMLScriptElement: Refusing to run script because the element is not connected.");
192
0
        return;
193
0
    }
194
195
    // 8. If any of the following are true:
196
    //    - el has a type attribute whose value is the empty string;
197
    //    - el has no type attribute but it has a language attribute and that attribute's value is the empty string; or
198
    //    - el has neither a type attribute nor a language attribute
199
0
    String script_block_type;
200
0
    auto maybe_type_attribute = attribute(HTML::AttributeNames::type);
201
0
    auto maybe_language_attribute = attribute(HTML::AttributeNames::language);
202
0
    if ((maybe_type_attribute.has_value() && maybe_type_attribute->is_empty())
203
0
        || (!maybe_type_attribute.has_value() && maybe_language_attribute.has_value() && maybe_language_attribute->is_empty())
204
0
        || (!maybe_type_attribute.has_value() && !maybe_language_attribute.has_value())) {
205
        // then let the script block's type string for this script element be "text/javascript".
206
0
        script_block_type = "text/javascript"_string;
207
0
    }
208
    // Otherwise, if el has a type attribute,
209
0
    else if (maybe_type_attribute.has_value()) {
210
        // then let the script block's type string be the value of that attribute with leading and trailing ASCII whitespace stripped.
211
0
        script_block_type = MUST(maybe_type_attribute->trim(Infra::ASCII_WHITESPACE));
212
0
    }
213
    // Otherwise, el has a non-empty language attribute;
214
0
    else if (maybe_language_attribute.has_value() && !maybe_language_attribute->is_empty()) {
215
        // let the script block's type string be the concatenation of "text/" and the value of el's language attribute.
216
0
        script_block_type = MUST(String::formatted("text/{}", maybe_language_attribute.value()));
217
0
    }
218
219
    // 9. If the script block's type string is a JavaScript MIME type essence match,
220
0
    if (MimeSniff::is_javascript_mime_type_essence_match(script_block_type)) {
221
        // then set el's type to "classic".
222
0
        m_script_type = ScriptType::Classic;
223
0
    }
224
    // 10. Otherwise, if the script block's type string is an ASCII case-insensitive match for the string "module",
225
0
    else if (Infra::is_ascii_case_insensitive_match(script_block_type, "module"sv)) {
226
        // then set el's type to "module".
227
0
        m_script_type = ScriptType::Module;
228
0
    }
229
    // 11. Otherwise, if the script block's type string is an ASCII case-insensitive match for the string "importmap",
230
0
    else if (Infra::is_ascii_case_insensitive_match(script_block_type, "importmap"sv)) {
231
        // then set el's type to "importmap".
232
0
        m_script_type = ScriptType::ImportMap;
233
0
    }
234
    // 12. Otherwise, return. (No script is executed, and el's type is left as null.)
235
0
    else {
236
0
        VERIFY(m_script_type == ScriptType::Null);
237
0
        return;
238
0
    }
239
240
    // 13. If parser document is non-null, then set el's parser document back to parser document and set el's force async to false.
241
0
    if (parser_document) {
242
0
        m_parser_document = parser_document;
243
0
        m_force_async = false;
244
0
    }
245
246
    // 14. Set el's already started to true.
247
0
    m_already_started = true;
248
249
    // 15. Set el's preparation-time document to its node document.
250
0
    m_preparation_time_document = &document();
251
252
    // 16. If parser document is non-null, and parser document is not equal to el's preparation-time document, then return.
253
0
    if (parser_document != nullptr && parser_document != m_preparation_time_document) {
254
0
        dbgln("HTMLScriptElement: Refusing to run script because the parser document is not the same as the preparation time document.");
255
0
        return;
256
0
    }
257
258
    // 17. If scripting is disabled for el, then return.
259
0
    if (is_scripting_disabled()) {
260
0
        dbgln("HTMLScriptElement: Refusing to run script because scripting is disabled.");
261
0
        return;
262
0
    }
263
264
    // 18. If el has a nomodule content attribute and its type is "classic", then return.
265
0
    if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::nomodule)) {
266
0
        dbgln("HTMLScriptElement: Refusing to run classic script because it has the nomodule attribute.");
267
0
        return;
268
0
    }
269
270
    // FIXME: 19. If el does not have a src content attribute, and the Should element's inline behavior be blocked by Content Security Policy?
271
    //            algorithm returns "Blocked" when given el, "script", and source text, then return. [CSP]
272
273
    // 20. If el has an event attribute and a for attribute, and el's type is "classic", then:
274
0
    if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::event) && has_attribute(HTML::AttributeNames::for_)) {
275
        // 1. Let for be the value of el's' for attribute.
276
0
        auto for_ = get_attribute_value(HTML::AttributeNames::for_);
277
278
        // 2. Let event be the value of el's event attribute.
279
0
        auto event = get_attribute_value(HTML::AttributeNames::event);
280
281
        // 3. Strip leading and trailing ASCII whitespace from event and for.
282
0
        for_ = MUST(for_.trim(Infra::ASCII_WHITESPACE));
283
0
        event = MUST(event.trim(Infra::ASCII_WHITESPACE));
284
285
        // 4. If for is not an ASCII case-insensitive match for the string "window", then return.
286
0
        if (!Infra::is_ascii_case_insensitive_match(for_, "window"sv)) {
287
0
            dbgln("HTMLScriptElement: Refusing to run classic script because the provided 'for' attribute is not equal to 'window'");
288
0
            return;
289
0
        }
290
291
        // 5. If event is not an ASCII case-insensitive match for either the string "onload" or the string "onload()", then return.
292
0
        if (!Infra::is_ascii_case_insensitive_match(event, "onload"sv)
293
0
            && !Infra::is_ascii_case_insensitive_match(event, "onload()"sv)) {
294
0
            dbgln("HTMLScriptElement: Refusing to run classic script because the provided 'event' attribute is not equal to 'onload' or 'onload()'");
295
0
            return;
296
0
        }
297
0
    }
298
299
    // 21. If el has a charset attribute, then let encoding be the result of getting an encoding from the value of the charset attribute.
300
    //     If el does not have a charset attribute, or if getting an encoding failed, then let encoding be el's node document's the encoding.
301
0
    Optional<String> encoding;
302
303
0
    if (has_attribute(HTML::AttributeNames::charset)) {
304
0
        auto charset = TextCodec::get_standardized_encoding(get_attribute_value(HTML::AttributeNames::charset));
305
0
        if (charset.has_value())
306
0
            encoding = String::from_utf8(*charset).release_value_but_fixme_should_propagate_errors();
307
0
    }
308
309
0
    if (!encoding.has_value()) {
310
0
        encoding = document().encoding_or_default();
311
0
    }
312
313
0
    VERIFY(encoding.has_value());
314
315
    // 22. Let classic script CORS setting be the current state of el's crossorigin content attribute.
316
0
    auto classic_script_cors_setting = m_crossorigin;
317
318
    // 23. Let module script credentials mode be the CORS settings attribute credentials mode for el's crossorigin content attribute.
319
0
    auto module_script_credential_mode = cors_settings_attribute_credentials_mode(m_crossorigin);
320
321
    // FIXME: 24. Let cryptographic nonce be el's [[CryptographicNonce]] internal slot's value.
322
323
    // 25. If el has an integrity attribute, then let integrity metadata be that attribute's value.
324
    //     Otherwise, let integrity metadata be the empty string.
325
0
    String integrity_metadata;
326
0
    if (auto maybe_integrity = attribute(HTML::AttributeNames::integrity); maybe_integrity.has_value()) {
327
0
        integrity_metadata = *maybe_integrity;
328
0
    }
329
330
    // 26. Let referrer policy be the current state of el's referrerpolicy content attribute.
331
0
    auto referrer_policy = m_referrer_policy;
332
333
    // 27. Let fetch priority be the current state of el's fetchpriority content attribute.
334
0
    auto fetch_priority = Fetch::Infrastructure::request_priority_from_string(get_attribute_value(HTML::AttributeNames::fetchpriority)).value_or(Fetch::Infrastructure::Request::Priority::Auto);
335
336
    // 28. Let parser metadata be "parser-inserted" if el is parser-inserted, and "not-parser-inserted" otherwise.
337
0
    auto parser_metadata = is_parser_inserted()
338
0
        ? Fetch::Infrastructure::Request::ParserMetadata::ParserInserted
339
0
        : Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted;
340
341
    // 29. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce,
342
    //     integrity metadata is integrity metadata, parser metadata is parser metadata,
343
    //     credentials mode is module script credentials mode, referrer policy is referrer policy,
344
    //     and fetch priority is fetch priority.
345
0
    ScriptFetchOptions options {
346
0
        .cryptographic_nonce = {}, // FIXME
347
0
        .integrity_metadata = move(integrity_metadata),
348
0
        .parser_metadata = parser_metadata,
349
0
        .credentials_mode = module_script_credential_mode,
350
0
        .referrer_policy = move(referrer_policy),
351
0
        .fetch_priority = move(fetch_priority),
352
0
    };
353
354
    // 30. Let settings object be el's node document's relevant settings object.
355
0
    auto& settings_object = document().relevant_settings_object();
356
357
    // 31. If el has a src content attribute, then:
358
0
    if (has_attribute(HTML::AttributeNames::src)) {
359
        // 1. If el's type is "importmap",
360
0
        if (m_script_type == ScriptType::ImportMap) {
361
            // then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.
362
0
            queue_an_element_task(HTML::Task::Source::DOMManipulation, [this] {
363
0
                dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
364
0
            });
365
0
            return;
366
0
        }
367
368
        // 2. Let src be the value of el's src attribute.
369
0
        auto src = get_attribute_value(HTML::AttributeNames::src);
370
371
        // 3. If src is the empty string, then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.
372
0
        if (src.is_empty()) {
373
0
            dbgln("HTMLScriptElement: Refusing to run script because the src attribute is empty.");
374
0
            queue_an_element_task(HTML::Task::Source::DOMManipulation, [this] {
375
0
                dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
376
0
            });
377
0
            return;
378
0
        }
379
380
        // 4. Set el's from an external file to true.
381
0
        m_from_an_external_file = true;
382
383
        // 5. Parse src relative to el's node document.
384
0
        auto url = document().parse_url(src);
385
386
        // 6. If the previous step failed, then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return. Otherwise, let url be the resulting URL record.
387
0
        if (!url.is_valid()) {
388
0
            dbgln("HTMLScriptElement: Refusing to run script because the src URL '{}' is invalid.", url);
389
0
            queue_an_element_task(HTML::Task::Source::DOMManipulation, [this] {
390
0
                dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
391
0
            });
392
0
            return;
393
0
        }
394
395
        // FIXME: 7. If el is potentially render-blocking, then block rendering on el.
396
397
        // 8. Set el's delaying the load event to true.
398
0
        begin_delaying_document_load_event(*m_preparation_time_document);
399
400
        // FIXME: 9. If el is currently render-blocking, then set options's render-blocking to true.
401
402
        // 10. Let onComplete given result be the following steps:
403
0
        OnFetchScriptComplete on_complete = create_on_fetch_script_complete(heap(), [this](auto result) {
404
            // 1. Mark as ready el given result.
405
0
            if (result)
406
0
                mark_as_ready(Result { *result });
407
0
            else
408
0
                mark_as_ready(ResultState::Null {});
409
0
        });
410
411
        // 11. Switch on el's type:
412
        // -> "classic"
413
0
        if (m_script_type == ScriptType::Classic) {
414
            // Fetch a classic script given url, settings object, options, classic script CORS setting, encoding, and onComplete.
415
0
            fetch_classic_script(*this, url, settings_object, move(options), classic_script_cors_setting, encoding.release_value(), on_complete).release_value_but_fixme_should_propagate_errors();
416
0
        }
417
        // -> "module"
418
0
        else if (m_script_type == ScriptType::Module) {
419
            // If el does not have an integrity attribute, then set options's integrity metadata to the result of resolving a module integrity metadata with url and settings object.
420
0
            if (!has_attribute(HTML::AttributeNames::integrity))
421
0
                options.integrity_metadata = MUST(resolve_a_module_integrity_metadata(url, settings_object));
422
423
            // Fetch an external module script graph given url, settings object, options, and onComplete.
424
0
            fetch_external_module_script_graph(realm(), url, settings_object, options, on_complete);
425
0
        }
426
0
    }
427
428
    // 32. If el does not have a src content attribute:
429
0
    if (!has_attribute(HTML::AttributeNames::src)) {
430
        // Let base URL be el's node document's document base URL.
431
0
        auto base_url = document().base_url();
432
433
        // 2. Switch on el's type:
434
        // -> "classic"
435
0
        if (m_script_type == ScriptType::Classic) {
436
            // 1. Let script be the result of creating a classic script using source text, settings object, base URL, and options.
437
            // FIXME: Pass options.
438
0
            auto script = ClassicScript::create(m_document->url().to_byte_string(), source_text, settings_object, base_url, m_source_line_number);
439
440
            // 2. Mark as ready el given script.
441
0
            mark_as_ready(Result(move(script)));
442
0
        }
443
        // -> "module"
444
0
        else if (m_script_type == ScriptType::Module) {
445
            // 1. Set el's delaying the load event to true.
446
0
            begin_delaying_document_load_event(*m_preparation_time_document);
447
448
0
            auto steps = create_on_fetch_script_complete(heap(), [this](auto result) {
449
                // 1. Mark as ready el given result.
450
0
                if (!result)
451
0
                    mark_as_ready(ResultState::Null {});
452
0
                else
453
0
                    mark_as_ready(Result(*result));
454
0
            });
455
456
            // 2. Fetch an inline module script graph, given source text, base URL, settings object, options, and with the following steps given result:
457
            // FIXME: Pass options
458
0
            fetch_inline_module_script_graph(realm(), m_document->url().to_byte_string(), source_text.to_byte_string(), base_url, document().relevant_settings_object(), steps);
459
0
        }
460
        // -> "importmap"
461
0
        else if (m_script_type == ScriptType::ImportMap) {
462
            // FIXME: need to check if relevant global object is a Window - is this correct?
463
0
            auto& global = relevant_global_object(*this);
464
465
            // 1. If el's relevant global object's import maps allowed is false, then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.
466
0
            if (is<Window>(global) && !verify_cast<Window>(global).import_maps_allowed()) {
467
0
                queue_an_element_task(HTML::Task::Source::DOMManipulation, [this] {
468
0
                    dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
469
0
                });
470
0
                return;
471
0
            }
472
473
            // 2. Set el's relevant global object's import maps allowed to false.
474
0
            if (is<Window>(global))
475
0
                verify_cast<Window>(global).set_import_maps_allowed(false);
476
477
            // 3. Let result be the result of creating an import map parse result given source text and base URL.
478
0
            auto result = ImportMapParseResult::create(realm(), source_text.to_byte_string(), base_url);
479
480
            // 4. Mark as ready el given result.
481
0
            mark_as_ready(Result(move(result)));
482
0
        }
483
0
    }
484
485
    // 33. If el's type is "classic" and el has a src attribute, or el's type is "module":
486
0
    if ((m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::src)) || m_script_type == ScriptType::Module) {
487
        // 1. Assert: el's result is "uninitialized".
488
        // FIXME: I believe this step to be a spec bug, and it should be removed: https://github.com/whatwg/html/issues/8534
489
490
        // 2. If el has an async attribute or el's force async is true:
491
0
        if (has_attribute(HTML::AttributeNames::async) || m_force_async) {
492
            // 1. Let scripts be el's preparation-time document's set of scripts that will execute as soon as possible.
493
            // 2. Append el to scripts.
494
0
            m_preparation_time_document->scripts_to_execute_as_soon_as_possible().append(*this);
495
496
            // 3. Set el's steps to run when the result is ready to the following:
497
0
            m_steps_to_run_when_the_result_is_ready = [this] {
498
                // 1. Execute the script element el.
499
0
                execute_script();
500
501
                // 2. Remove el from scripts.
502
0
                m_preparation_time_document->scripts_to_execute_as_soon_as_possible().remove_first_matching([this](auto& entry) {
503
0
                    return entry.ptr() == this;
504
0
                });
505
0
            };
506
0
        }
507
508
        // 3. Otherwise, if el is not parser-inserted:
509
0
        else if (!is_parser_inserted()) {
510
            // 1. Let scripts be el's preparation-time document's list of scripts that will execute in order as soon as possible.
511
            // 2. Append el to scripts.
512
0
            m_preparation_time_document->scripts_to_execute_in_order_as_soon_as_possible().append(*this);
513
514
            // 3. Set el's steps to run when the result is ready to the following:
515
0
            m_steps_to_run_when_the_result_is_ready = [this] {
516
0
                auto& scripts = m_preparation_time_document->scripts_to_execute_in_order_as_soon_as_possible();
517
                // 1. If scripts[0] is not el, then abort these steps.
518
0
                if (scripts[0] != this)
519
0
                    return;
520
521
                // 2. While scripts is not empty, and scripts[0]'s result is not "uninitialized":
522
0
                while (!scripts.is_empty() && !scripts[0]->m_result.has<ResultState::Uninitialized>()) {
523
                    // 1. Execute the script element scripts[0].
524
0
                    scripts[0]->execute_script();
525
526
                    // 2. Remove scripts[0].
527
0
                    scripts.take_first();
528
0
                }
529
0
            };
530
0
        }
531
532
        // 4. Otherwise, if el has a defer attribute or el's type is "module":
533
0
        else if (has_attribute(HTML::AttributeNames::defer) || m_script_type == ScriptType::Module) {
534
            // 1. Append el to its parser document's list of scripts that will execute when the document has finished parsing.
535
0
            m_parser_document->add_script_to_execute_when_parsing_has_finished({}, *this);
536
537
            // 2. Set el's steps to run when the result is ready to the following:
538
0
            m_steps_to_run_when_the_result_is_ready = [this] {
539
                // set el's ready to be parser-executed to true. (The parser will handle executing the script.)
540
0
                m_ready_to_be_parser_executed = true;
541
0
            };
542
0
        }
543
544
        // 5. Otherwise:
545
0
        else {
546
            // 1. Set el's parser document's pending parsing-blocking script to el.
547
0
            m_parser_document->set_pending_parsing_blocking_script(this);
548
549
            // FIXME: 2. Block rendering on el.
550
551
            // 3. Set el's steps to run when the result is ready to the following:
552
0
            m_steps_to_run_when_the_result_is_ready = [this] {
553
                // set el's ready to be parser-executed to true. (The parser will handle executing the script.)
554
0
                m_ready_to_be_parser_executed = true;
555
0
            };
556
0
        }
557
0
    }
558
559
    // 34. Otherwise:
560
0
    else {
561
        // 1. Assert: el's result is not "uninitialized".
562
0
        VERIFY(!m_result.has<ResultState::Uninitialized>());
563
564
        // 2. If all of the following are true:
565
        //    - el's type is "classic";
566
        //    - el is parser-inserted;
567
        //    - el's parser document has a style sheet that is blocking scripts; and
568
        //    FIXME: - either the parser that created el is an XML parser, or it's an HTML parser whose script nesting level is not greater than one,
569
        //    then:
570
0
        if (m_script_type == ScriptType::Classic
571
0
            && is_parser_inserted()
572
0
            && m_parser_document->has_a_style_sheet_that_is_blocking_scripts()) {
573
            // 1. Set el's parser document's pending parsing-blocking script to el.
574
0
            m_parser_document->set_pending_parsing_blocking_script(this);
575
576
            // 2. Set el's ready to be parser-executed to true. (The parser will handle executing the script.)
577
0
            m_ready_to_be_parser_executed = true;
578
0
        }
579
580
        // 3. Otherwise,
581
0
        else {
582
            // immediately execute the script element el, even if other scripts are already executing.
583
0
            execute_script();
584
0
        }
585
0
    }
586
0
}
587
588
void HTMLScriptElement::inserted()
589
0
{
590
0
    if (!is_parser_inserted()) {
591
        // FIXME: Only do this if the element was previously not connected.
592
0
        if (is_connected()) {
593
0
            prepare_script();
594
0
        }
595
0
    }
596
0
    HTMLElement::inserted();
597
0
}
598
599
// https://html.spec.whatwg.org/multipage/scripting.html#mark-as-ready
600
void HTMLScriptElement::mark_as_ready(Result result)
601
0
{
602
    // 1. Set el's result to result.
603
0
    m_result = move(result);
604
605
    // 2. If el's steps to run when the result is ready are not null, then run them.
606
0
    if (m_steps_to_run_when_the_result_is_ready)
607
0
        m_steps_to_run_when_the_result_is_ready();
608
609
    // 3. Set el's steps to run when the result is ready to null.
610
0
    m_steps_to_run_when_the_result_is_ready = nullptr;
611
612
    // 4. Set el's delaying the load event to false.
613
0
    m_document_load_event_delayer.clear();
614
0
}
615
616
void HTMLScriptElement::unmark_as_already_started(Badge<DOM::Range>)
617
0
{
618
0
    m_already_started = false;
619
0
}
620
621
void HTMLScriptElement::unmark_as_parser_inserted(Badge<DOM::Range>)
622
0
{
623
0
    m_parser_document = nullptr;
624
0
}
625
626
// https://html.spec.whatwg.org/multipage/scripting.html#dom-script-async
627
bool HTMLScriptElement::async() const
628
0
{
629
    // 1. If this's force async is true, then return true.
630
0
    if (m_force_async)
631
0
        return true;
632
633
    // 2. If this's async content attribute is present, then return true.
634
0
    if (has_attribute(HTML::AttributeNames::async))
635
0
        return true;
636
637
    // 3. Return false.
638
0
    return false;
639
0
}
640
641
void HTMLScriptElement::set_async(bool async)
642
0
{
643
    // 1. Set this's force async to false.
644
0
    m_force_async = false;
645
646
    // 2. If the given value is true, then set this's async content attribute to the empty string.
647
0
    if (async) {
648
0
        MUST(set_attribute(HTML::AttributeNames::async, ""_string));
649
0
    }
650
    // 3. Otherwise, remove this's async content attribute.
651
0
    else {
652
0
        remove_attribute(HTML::AttributeNames::async);
653
0
    }
654
0
}
655
656
}