1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2003-2023 Apple Inc. All rights reserved.
* Copyright (C) 2008 Nikolas Zimmermann <zimmermann@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "ScriptElement.h"
#include "CachedResourceLoader.h"
#include "CachedResourceRequest.h"
#include "CachedScript.h"
#include "CommonVM.h"
#include "ContentSecurityPolicy.h"
#include "CrossOriginAccessControl.h"
#include "CurrentScriptIncrementer.h"
#include "DocumentInlines.h"
#include "ElementInlines.h"
#include "Event.h"
#include "EventLoop.h"
#include "EventNames.h"
#include "FrameLoader.h"
#include "HTMLNames.h"
#include "HTMLScriptElement.h"
#include "IgnoreDestructiveWriteCountIncrementer.h"
#include "InlineClassicScript.h"
#include "LoadableClassicScript.h"
#include "LoadableModuleScript.h"
#include "LocalFrame.h"
#include "MIMETypeRegistry.h"
#include "ModuleFetchParameters.h"
#include "Page.h"
#include "PendingScript.h"
#include "SVGElementTypeHelpers.h"
#include "SVGScriptElement.h"
#include "ScriptController.h"
#include "ScriptDisallowedScope.h"
#include "ScriptRunner.h"
#include "ScriptSourceCode.h"
#include "ScriptableDocumentParser.h"
#include "Settings.h"
#include "TextNodeTraversal.h"
#include "TrustedType.h"
#include <JavaScriptCore/ImportMap.h>
#include <wtf/RuntimeApplicationChecks.h>
#include <wtf/Scope.h>
#include <wtf/SystemTracing.h>
#include <wtf/text/MakeString.h>
namespace WebCore {
static const auto maxUserGesturePropagationTime = 1_s;
ScriptElement::ScriptElement(Element& element, bool parserInserted, bool alreadyStarted)
: m_element(element)
, m_parserInserted(parserInserted ? ParserInserted::Yes : ParserInserted::No)
, m_alreadyStarted(alreadyStarted)
, m_forceAsync(!parserInserted)
, m_creationTime(MonotonicTime::now())
, m_userGestureToken(UserGestureIndicator::currentUserGesture())
{
Ref vm = commonVM();
m_taintedOrigin = computeNewSourceTaintedOriginFromStack(vm, vm->topCallFrame);
if (parserInserted) {
Ref document = element.document();
if (RefPtr parser = document->scriptableDocumentParser(); parser && !document->isInDocumentWrite())
m_startLineNumber = parser->textPosition().m_line;
}
}
void ScriptElement::didFinishInsertingNode()
{
if (m_parserInserted == ParserInserted::No)
prepareScript(); // FIXME: Provide a real starting line number here.
}
void ScriptElement::childrenChanged(const ContainerNode::ChildChange& childChange)
{
if (m_parserInserted == ParserInserted::No && childChange.isInsertion() && element().isConnected())
prepareScript(); // FIXME: Provide a real starting line number here.
if (childChange.source == ContainerNode::ChildChange::Source::API)
m_childrenChangedByAPI = true;
}
void ScriptElement::finishParsingChildren()
{
if (!m_childrenChangedByAPI)
m_trustedScriptText = scriptContent();
}
void ScriptElement::handleSourceAttribute(const String& sourceURL)
{
if (ignoresLoadRequest() || sourceURL.isEmpty())
return;
prepareScript(); // FIXME: Provide a real starting line number here.
}
void ScriptElement::handleAsyncAttribute()
{
m_forceAsync = false;
}
void ScriptElement::dispatchErrorEvent()
{
protectedElement()->dispatchEvent(Event::create(eventNames().errorEvent, Event::CanBubble::No, Event::IsCancelable::No));
}
// https://html.spec.whatwg.org/C#prepare-the-script-element (Steps 8-12)
std::optional<ScriptType> ScriptElement::determineScriptType(const String& type, const String& language, bool isHTMLDocument)
{
// Step 8. If any of the following are true:
// - el has a type attribute whose value is the empty string;
// - el has no type attribute but it has a language attribute and that attribute's value is the empty string; or
// - el has neither a type attribute nor a language attribute,
// then let the script block's type string for this script element be "text/javascript".
if (type.isNull()) {
if (language.isEmpty())
return ScriptType::Classic;
if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(makeString("text/"_s, language)))
return ScriptType::Classic;
return std::nullopt;
}
if (type.isEmpty())
return ScriptType::Classic; // Assume text/javascript.
// Step 9. If the script block's type string is a JavaScript MIME type essence match, then set el's type to "classic".
if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(type.trim(isASCIIWhitespace)))
return ScriptType::Classic;
// FIXME: XHTML spec defines "defer" attribute. But WebKit does not implement it for a long time.
// And module tag also uses defer attribute semantics. We disable script type="module" for non HTML document.
// Once "defer" is implemented, we can reconsider enabling modules in XHTML.
// https://bugs.webkit.org/show_bug.cgi?id=123387
if (!isHTMLDocument)
return std::nullopt;
// Step 10. Otherwise, if the script block's type string is an ASCII case-insensitive match for the string "module", then set el's type to "module".
if (equalLettersIgnoringASCIICase(type, "module"_s))
return ScriptType::Module;
// Step 11. Otherwise, if the script block's type string is an ASCII case-insensitive match for the string "importmap", then set el's type to "importmap".
if (equalLettersIgnoringASCIICase(type, "importmap"_s))
return ScriptType::ImportMap;
return std::nullopt;
}
std::optional<ScriptType> ScriptElement::determineScriptType() const
{
return determineScriptType(typeAttributeValue(), languageAttributeValue(), element().document().isHTMLDocument());
}
// https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
bool ScriptElement::prepareScript(const TextPosition& scriptStartPosition)
{
if (m_alreadyStarted)
return false;
bool wasParserInserted;
if (m_parserInserted == ParserInserted::Yes) {
wasParserInserted = true;
m_parserInserted = ParserInserted::No;
} else
wasParserInserted = false;
if (wasParserInserted && !hasAsyncAttribute())
m_forceAsync = true;
String sourceText = scriptContent();
Ref element = this->element();
Ref context = *element->scriptExecutionContext();
if (context->settingsValues().trustedTypesEnabled && sourceText != m_trustedScriptText) {
auto trustedText = trustedTypeCompliantString(TrustedType::TrustedScript, context, sourceText, is<HTMLScriptElement>(element) ? "HTMLScriptElement text"_s : "SVGScriptElement text"_s);
if (trustedText.hasException())
return false;
sourceText = trustedText.releaseReturnValue();
}
if (!hasSourceAttribute() && sourceText.isEmpty())
return false;
if (!element->isConnected())
return false;
ScriptType scriptType = ScriptType::Classic;
if (std::optional<ScriptType> result = determineScriptType())
scriptType = result.value();
else
return false;
m_scriptType = scriptType;
if (wasParserInserted) {
m_parserInserted = ParserInserted::Yes;
m_forceAsync = false;
}
m_alreadyStarted = true;
// FIXME: If script is parser inserted, verify it's still in the original document.
Ref document = element->document();
// FIXME: Eventually we'd like to evaluate scripts which are inserted into a
// viewless document but this'll do for now.
// See http://bugs.webkit.org/show_bug.cgi?id=5727
if (!document->frame())
return false;
if (scriptType == ScriptType::Classic && hasNoModuleAttribute())
return false;
m_preparationTimeDocumentIdentifier = document->identifier();
if (!document->frame()->script().canExecuteScripts(ReasonForCallingCanExecuteScripts::AboutToExecuteScript))
return false;
if (scriptType == ScriptType::Classic && isScriptPreventedByAttributes())
return false;
// According to the spec, the module tag ignores the "charset" attribute as the same to the worker's
// importScript. But WebKit supports the "charset" for importScript intentionally. So to be consistent,
// even for the module tags, we handle the "charset" attribute.
if (auto attributeValue = charsetAttributeValue(); !attributeValue.isEmpty())
m_characterEncoding = WTFMove(attributeValue);
else
m_characterEncoding = document->charset();
switch (scriptType) {
case ScriptType::Classic: {
if (hasSourceAttribute()) {
if (!requestClassicScript(sourceAttributeValue()))
return false;
potentiallyBlockRendering();
}
break;
}
case ScriptType::Module: {
if (!requestModuleScript(scriptStartPosition))
return false;
potentiallyBlockRendering();
break;
}
case ScriptType::ImportMap: {
// If the element’s node document's acquiring import maps is false, then queue a task to fire an event named error at the element, and return.
if (hasSourceAttribute()) {
element->protectedDocument()->checkedEventLoop()->queueTask(TaskSource::DOMManipulation, [protectedThis = Ref { *this }] {
protectedThis->dispatchErrorEvent();
});
return false;
}
break;
}
}
updateTaintedOriginFromSourceURL();
// All the inlined module script is handled by requestModuleScript. It produces LoadableModuleScript and inlined module script
// is handled as the same to the external module script.
bool isClassicExternalScript = scriptType == ScriptType::Classic && hasSourceAttribute();
bool isParserInsertedDeferredScript = ((isClassicExternalScript && hasDeferAttribute()) || scriptType == ScriptType::Module)
&& m_parserInserted == ParserInserted::Yes && !hasAsyncAttribute();
if (isParserInsertedDeferredScript) {
m_willExecuteWhenDocumentFinishedParsing = true;
m_willBeParserExecuted = true;
} else if (isClassicExternalScript && m_parserInserted == ParserInserted::Yes && !hasAsyncAttribute()) {
ASSERT(scriptType == ScriptType::Classic);
m_willBeParserExecuted = true;
} else if ((isClassicExternalScript || scriptType == ScriptType::Module) && !hasAsyncAttribute() && !m_forceAsync) {
m_willExecuteInOrder = true;
ASSERT(m_loadableScript);
document->protectedScriptRunner()->queueScriptForExecution(*this, *protectedLoadableScript(), ScriptRunner::IN_ORDER_EXECUTION);
} else if (hasSourceAttribute() || scriptType == ScriptType::Module) {
ASSERT(m_loadableScript);
ASSERT(hasAsyncAttribute() || m_forceAsync);
document->protectedScriptRunner()->queueScriptForExecution(*this, *protectedLoadableScript(), ScriptRunner::ASYNC_EXECUTION);
} else if (!hasSourceAttribute() && m_parserInserted == ParserInserted::Yes && !document->haveStylesheetsLoaded()) {
ASSERT(scriptType == ScriptType::Classic || scriptType == ScriptType::ImportMap);
m_willBeParserExecuted = true;
m_readyToBeParserExecuted = true;
} else {
ASSERT(scriptType == ScriptType::Classic || scriptType == ScriptType::ImportMap);
TextPosition position = document->isInDocumentWrite() ? TextPosition() : scriptStartPosition;
if (scriptType == ScriptType::Classic)
executeClassicScript(ScriptSourceCode(sourceText, m_taintedOrigin, URL(document->url()), position, JSC::SourceProviderSourceType::Program, InlineClassicScript::create(*this)));
else
registerImportMap(ScriptSourceCode(sourceText, m_taintedOrigin, URL(document->url()), position, JSC::SourceProviderSourceType::ImportMap));
}
return true;
}
void ScriptElement::updateTaintedOriginFromSourceURL()
{
if (m_taintedOrigin == JSC::SourceTaintedOrigin::KnownTainted)
return;
Ref document = element().document();
RefPtr page = document->page();
if (!page)
return;
if (!page->requiresScriptTelemetryForURL(hasSourceAttribute() ? document->completeURL(sourceAttributeValue()) : document->url()))
return;
m_taintedOrigin = JSC::SourceTaintedOrigin::KnownTainted;
}
bool ScriptElement::requestClassicScript(const String& sourceURL)
{
auto element = protectedElement();
ASSERT(element->isConnected());
ASSERT(!m_loadableScript);
Ref document = element->document();
if (!StringView(sourceURL).containsOnly<isASCIIWhitespace<UChar>>()) {
auto script = LoadableClassicScript::create(element->nonce(), element->attributeWithoutSynchronization(HTMLNames::integrityAttr), referrerPolicy(), fetchPriority(),
element->attributeWithoutSynchronization(HTMLNames::crossoriginAttr), scriptCharset(), element->localName(), element->isInUserAgentShadowTree(), hasAsyncAttribute());
auto scriptURL = document->completeURL(sourceURL);
document->willLoadScriptElement(scriptURL);
if (!document->checkedContentSecurityPolicy()->allowNonParserInsertedScripts(scriptURL, URL(), m_startLineNumber, element->nonce(), script->integrity(), String(), m_parserInserted))
return false;
if (script->load(document, scriptURL)) {
m_loadableScript = WTFMove(script);
m_isExternalScript = true;
}
}
if (m_loadableScript)
return true;
document->eventLoop().queueTask(TaskSource::DOMManipulation, [protectedThis = Ref { *this }] {
protectedThis->dispatchErrorEvent();
});
return false;
}
bool ScriptElement::requestModuleScript(const TextPosition& scriptStartPosition)
{
// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
// Module is always CORS request. If attribute is not given, it should be same-origin credential.
Ref element = this->element();
Ref document = element->document();
auto nonce = element->nonce();
auto crossOriginMode = element->attributeWithoutSynchronization(HTMLNames::crossoriginAttr);
if (crossOriginMode.isNull())
crossOriginMode = ScriptElementCachedScriptFetcher::defaultCrossOriginModeForModule;
if (hasSourceAttribute()) {
ASSERT(element->isConnected());
String sourceURL = sourceAttributeValue();
if (StringView(sourceURL).containsOnly<isASCIIWhitespace<UChar>>()) {
dispatchErrorEvent();
return false;
}
auto moduleScriptRootURL = document->completeURL(sourceURL);
if (!moduleScriptRootURL.isValid()) {
dispatchErrorEvent();
return false;
}
m_isExternalScript = true;
AtomString integrity = element->attributeWithoutSynchronization(HTMLNames::integrityAttr);
if (integrity.isNull())
integrity = AtomString { document->globalObject()->importMap().integrityForURL(moduleScriptRootURL) };
Ref script = LoadableModuleScript::create(nonce, integrity, referrerPolicy(), fetchPriority(), crossOriginMode,
scriptCharset(), element->localName(), element->isInUserAgentShadowTree());
m_loadableScript = script.copyRef();
if (RefPtr frame = element->document().frame())
frame->checkedScript()->loadModuleScript(script, moduleScriptRootURL, script->parameters());
return true;
}
Ref script = LoadableModuleScript::create(nonce, emptyAtom(), referrerPolicy(), fetchPriority(), crossOriginMode, scriptCharset(), element->localName(), element->isInUserAgentShadowTree());
TextPosition position = document->isInDocumentWrite() ? TextPosition() : scriptStartPosition;
ScriptSourceCode sourceCode(scriptContent(), m_taintedOrigin, URL(document->url()), position, JSC::SourceProviderSourceType::Module, script.copyRef());
ASSERT(document->contentSecurityPolicy());
{
CheckedRef contentSecurityPolicy = *document->contentSecurityPolicy();
if (!contentSecurityPolicy->allowNonParserInsertedScripts(URL(), document->url(), m_startLineNumber, element->nonce(), script->parameters().integrity(), sourceCode.source(), m_parserInserted))
return false;
if (!contentSecurityPolicy->allowInlineScript(document->url().string(), m_startLineNumber, sourceCode.source(), element, nonce, element->isInUserAgentShadowTree()))
return false;
}
m_loadableScript = script.copyRef();
if (RefPtr frame = document->frame())
frame->checkedScript()->loadModuleScript(script, sourceCode);
return true;
}
void ScriptElement::executeClassicScript(const ScriptSourceCode& sourceCode)
{
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(ScriptDisallowedScope::InMainThread::isScriptAllowed());
ASSERT(m_alreadyStarted);
if (sourceCode.isEmpty())
return;
Ref element = this->element();
Ref document = element->document();
if (!m_isExternalScript) {
ASSERT(document->contentSecurityPolicy());
CheckedRef contentSecurityPolicy = *document->contentSecurityPolicy();
if (!contentSecurityPolicy->allowNonParserInsertedScripts(URL(), document->url(), m_startLineNumber, element->nonce(), emptyString(), sourceCode.source(), m_parserInserted))
return;
if (!contentSecurityPolicy->allowInlineScript(document->url().string(), m_startLineNumber, sourceCode.source(), element, element->nonce(), element->isInUserAgentShadowTree()))
return;
}
RefPtr frame = document->frame();
if (!frame)
return;
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript ? document.ptr() : nullptr);
CurrentScriptIncrementer currentScriptIncrementer(document, *this);
WTFBeginSignpost(this, ExecuteScriptElement, "executing classic script from URL: %" PRIVATE_LOG_STRING " async: %d defer: %d", m_isExternalScript ? sourceCode.url().string().utf8().data() : "inline", hasAsyncAttribute(), hasDeferAttribute());
frame->checkedScript()->evaluateIgnoringException(sourceCode);
WTFEndSignpost(this, ExecuteScriptElement);
}
void ScriptElement::registerImportMap(const ScriptSourceCode& sourceCode)
{
// https://html.spec.whatwg.org/#register-an-import-map
ASSERT(m_alreadyStarted);
ASSERT(scriptType() == ScriptType::ImportMap);
Ref element = this->element();
Ref document = element->document();
RefPtr frame = document->frame();
if (sourceCode.isEmpty()) {
dispatchErrorEvent();
return;
}
if (!m_isExternalScript) {
ASSERT(document->contentSecurityPolicy());
CheckedRef contentSecurityPolicy = *document->contentSecurityPolicy();
if (!contentSecurityPolicy->allowNonParserInsertedScripts(URL(), document->url(), m_startLineNumber, element->nonce(), emptyString(), sourceCode.source(), m_parserInserted))
return;
if (!contentSecurityPolicy->allowInlineScript(document->url().string(), m_startLineNumber, sourceCode.source(), element, element->nonce(), element->isInUserAgentShadowTree()))
return;
}
if (!frame)
return;
WTFBeginSignpost(this, RegisterImportMap, "registering import-map from URL: %" PRIVATE_LOG_STRING " async: %d defer: %d", m_isExternalScript ? sourceCode.url().string().utf8().data() : "inline", hasAsyncAttribute(), hasDeferAttribute());
frame->checkedScript()->registerImportMap(sourceCode, document->baseURL());
WTFEndSignpost(this, RegisterImportMap);
}
void ScriptElement::executeModuleScript(LoadableModuleScript& loadableModuleScript)
{
// https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block
ASSERT(!loadableModuleScript.hasError());
Ref document = element().document();
RefPtr frame = document->frame();
if (!frame)
return;
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(document.ptr());
CurrentScriptIncrementer currentScriptIncrementer(document, *this);
WTFBeginSignpost(this, ExecuteScriptElement, "executing module script");
frame->script().linkAndEvaluateModuleScript(loadableModuleScript);
WTFEndSignpost(this, ExecuteScriptElement, "executing module script");
}
void ScriptElement::dispatchLoadEventRespectingUserGestureIndicator()
{
if (MonotonicTime::now() - m_creationTime > maxUserGesturePropagationTime) {
dispatchLoadEvent();
return;
}
UserGestureIndicator indicator(m_userGestureToken);
dispatchLoadEvent();
}
void ScriptElement::executeScriptAndDispatchEvent(LoadableScript& loadableScript)
{
if (auto error = loadableScript.takeError()) {
// There are three types of errors in script loading, fetch error, parse error, and script error.
// 1. Fetch error dispatches an error event on <script> tag, but not on window.
// 2. Parse error dispatches an error event on window, but not on <script>. And
// it still dispatches a load event on <script>.
// 3. Script error dispatches an error event on window.
switch (error->type) {
// Fetch error
case LoadableScript::ErrorType::Fetch:
case LoadableScript::ErrorType::CrossOriginLoad:
case LoadableScript::ErrorType::MIMEType:
case LoadableScript::ErrorType::Nosniff:
case LoadableScript::ErrorType::FailedIntegrityCheck: {
// https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block
// When the script is "null" due to a fetch error, an error event
// should be dispatched for the script element.
if (std::optional<LoadableScript::ConsoleMessage> message = error->consoleMessage)
element().protectedDocument()->addConsoleMessage(message->source, message->level, message->message);
dispatchErrorEvent();
break;
}
// Parse error
case LoadableScript::ErrorType::Resolve: {
if (RefPtr frame = element().document().frame())
frame->checkedScript()->reportExceptionFromScriptError(error.value(), loadableScript.isModuleScript());
dispatchLoadEventRespectingUserGestureIndicator();
break;
}
// Script error
case LoadableScript::ErrorType::Script: {
// https://html.spec.whatwg.org/multipage/webappapis.html#report-the-exception
// An error value is present when there is a load failure that was
// not triggered during fetching. In this case, we need to report
// the exception to the global object.
if (RefPtr frame = element().document().frame())
frame->checkedScript()->reportExceptionFromScriptError(error.value(), loadableScript.isModuleScript());
break;
}
}
} else if (!loadableScript.wasCanceled()) {
loadableScript.execute(*this);
dispatchLoadEventRespectingUserGestureIndicator();
}
}
void ScriptElement::executePendingScript(PendingScript& pendingScript)
{
unblockRendering();
RefPtr loadableScript = pendingScript.loadableScript();
Ref document = element().document();
if (document->identifier() != m_preparationTimeDocumentIdentifier) {
document->addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Not executing script because it moved between documents during fetching"_s);
} else {
if (loadableScript)
executeScriptAndDispatchEvent(*loadableScript);
else {
ASSERT(!pendingScript.hasError());
ASSERT_WITH_MESSAGE(scriptType() == ScriptType::Classic || scriptType() == ScriptType::ImportMap, "Module script always have a loadableScript pointer.");
if (scriptType() == ScriptType::Classic)
executeClassicScript(ScriptSourceCode(scriptContent(), m_taintedOrigin, URL(document->url()), pendingScript.startingPosition(), JSC::SourceProviderSourceType::Program, InlineClassicScript::create(*this)));
else
registerImportMap(ScriptSourceCode(scriptContent(), m_taintedOrigin, URL(document->url()), pendingScript.startingPosition(), JSC::SourceProviderSourceType::ImportMap));
dispatchLoadEventRespectingUserGestureIndicator();
}
}
}
bool ScriptElement::ignoresLoadRequest() const
{
return m_alreadyStarted || m_isExternalScript || m_parserInserted == ParserInserted::Yes || !element().isConnected();
}
String ScriptElement::scriptContent() const
{
return TextNodeTraversal::childTextContent(protectedElement());
}
void ScriptElement::setTrustedScriptText(const String& text)
{
m_trustedScriptText = text;
}
void ScriptElement::ref() const
{
element().ref();
}
void ScriptElement::deref() const
{
element().deref();
}
bool isScriptElement(Element& element)
{
return is<HTMLScriptElement>(element) || is<SVGScriptElement>(element);
}
ScriptElement* dynamicDowncastScriptElement(Element& element)
{
if (auto* htmlElement = dynamicDowncast<HTMLScriptElement>(element))
return htmlElement;
return dynamicDowncast<SVGScriptElement>(element);
}
}
|