HTMLScriptElement.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Debug.h>
  27. #include <AK/StringBuilder.h>
  28. #include <LibJS/Parser.h>
  29. #include <LibTextCodec/Decoder.h>
  30. #include <LibWeb/DOM/Document.h>
  31. #include <LibWeb/DOM/Event.h>
  32. #include <LibWeb/DOM/ShadowRoot.h>
  33. #include <LibWeb/DOM/Text.h>
  34. #include <LibWeb/HTML/EventNames.h>
  35. #include <LibWeb/HTML/HTMLScriptElement.h>
  36. #include <LibWeb/Loader/ResourceLoader.h>
  37. namespace Web::HTML {
  38. HTMLScriptElement::HTMLScriptElement(DOM::Document& document, const QualifiedName& qualified_name)
  39. : HTMLElement(document, qualified_name)
  40. {
  41. }
  42. HTMLScriptElement::~HTMLScriptElement()
  43. {
  44. }
  45. void HTMLScriptElement::set_parser_document(Badge<HTMLDocumentParser>, DOM::Document& document)
  46. {
  47. m_parser_document = document;
  48. }
  49. void HTMLScriptElement::set_non_blocking(Badge<HTMLDocumentParser>, bool non_blocking)
  50. {
  51. m_non_blocking = non_blocking;
  52. }
  53. void HTMLScriptElement::execute_script()
  54. {
  55. if (m_preparation_time_document.ptr() != &document()) {
  56. dbgln("HTMLScriptElement: Refusing to run script because the preparation time document is not the same as the node document.");
  57. return;
  58. }
  59. if (m_script_source.is_null()) {
  60. dbgln("HTMLScriptElement: Refusing to run script because the script source is null.");
  61. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  62. return;
  63. }
  64. bool incremented_destructive_writes_counter = false;
  65. if (m_from_an_external_file || m_script_type == ScriptType::Module) {
  66. document().increment_ignore_destructive_writes_counter();
  67. incremented_destructive_writes_counter = true;
  68. }
  69. if (m_script_type == ScriptType::Classic) {
  70. auto old_current_script = document().current_script();
  71. if (!is<DOM::ShadowRoot>(root()))
  72. document().set_current_script({}, this);
  73. else
  74. document().set_current_script({}, nullptr);
  75. if (m_from_an_external_file)
  76. dbgln<HTML_SCRIPT_DEBUG>("HTMLScriptElement: Running script {}", attribute(HTML::AttributeNames::src));
  77. else
  78. dbgln<HTML_SCRIPT_DEBUG>("HTMLScriptElement: Running inline script");
  79. document().run_javascript(m_script_source);
  80. document().set_current_script({}, old_current_script);
  81. } else {
  82. ASSERT(!document().current_script());
  83. TODO();
  84. }
  85. if (incremented_destructive_writes_counter)
  86. document().decrement_ignore_destructive_writes_counter();
  87. if (m_from_an_external_file)
  88. dispatch_event(DOM::Event::create(HTML::EventNames::load));
  89. }
  90. // https://mimesniff.spec.whatwg.org/#javascript-mime-type-essence-match
  91. static bool is_javascript_mime_type_essence_match(const String& mime_type)
  92. {
  93. // FIXME: This operates on the whole mime type, instead of just the essence. https://mimesniff.spec.whatwg.org/#mime-type-essence
  94. // It'd probably be best to make a helper class for mime types, since there is a whole spec about mime types.
  95. auto lowercase_mime_type = mime_type.to_lowercase();
  96. return lowercase_mime_type.is_one_of("application/ecmascript", "application/javascript", "application/x-ecmascript", "application/x-javascript", "text/ecmascript", "text/javascript", "text/javascript1.0", "text/javascript1.1", "text/javascript1.2", "text/javascript1.3", "text/javascript1.4", "text/javascript1.5", "text/jscript", "text/livescript", "text/x-ecmascript", "text/x-javascript");
  97. }
  98. // https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
  99. void HTMLScriptElement::prepare_script(Badge<HTMLDocumentParser>)
  100. {
  101. if (m_already_started) {
  102. dbgln("HTMLScriptElement: Refusing to run script because it has already started.");
  103. return;
  104. }
  105. RefPtr<DOM::Document> parser_document = m_parser_document.ptr();
  106. m_parser_document = nullptr;
  107. if (parser_document && !has_attribute(HTML::AttributeNames::async)) {
  108. m_non_blocking = true;
  109. }
  110. auto source_text = child_text_content();
  111. if (!has_attribute(HTML::AttributeNames::src) && source_text.is_empty()) {
  112. dbgln("HTMLScriptElement: Refusing to run empty script.");
  113. return;
  114. }
  115. if (!is_connected()) {
  116. dbgln("HTMLScriptElement: Refusing to run script because the element is not connected.");
  117. return;
  118. }
  119. String script_block_type;
  120. bool has_type = has_attribute(HTML::AttributeNames::type);
  121. bool has_language = has_attribute(HTML::AttributeNames::language);
  122. if ((has_type && attribute(HTML::AttributeNames::type).is_empty())
  123. || (!has_type && has_language && attribute(HTML::AttributeNames::language).is_empty())
  124. || (!has_type && !has_language)) {
  125. script_block_type = "text/javascript";
  126. } else if (has_type) {
  127. script_block_type = attribute(HTML::AttributeNames::type).trim_whitespace();
  128. } else if (!attribute(HTML::AttributeNames::language).is_empty()) {
  129. script_block_type = String::formatted("text/{}", attribute(HTML::AttributeNames::language));
  130. }
  131. if (is_javascript_mime_type_essence_match(script_block_type)) {
  132. m_script_type = ScriptType::Classic;
  133. } else if (script_block_type.equals_ignoring_case("module")) {
  134. m_script_type = ScriptType::Module;
  135. } else {
  136. dbgln("HTMLScriptElement: Refusing to run script because the type '{}' is not recognized.", script_block_type);
  137. return;
  138. }
  139. if (parser_document) {
  140. m_parser_document = *parser_document;
  141. m_non_blocking = false;
  142. }
  143. m_already_started = true;
  144. m_preparation_time_document = document();
  145. if (parser_document && parser_document.ptr() != m_preparation_time_document.ptr()) {
  146. dbgln("HTMLScriptElement: Refusing to run script because the parser document is not the same as the preparation time document.");
  147. return;
  148. }
  149. // FIXME: Check if scripting is disabled, if so return
  150. if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::nomodule)) {
  151. dbgln("HTMLScriptElement: Refusing to run classic script because it has the nomodule attribute.");
  152. return;
  153. }
  154. // FIXME: Check CSP
  155. if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::event) && has_attribute(HTML::AttributeNames::for_)) {
  156. auto for_ = attribute(HTML::AttributeNames::for_).trim_whitespace();
  157. auto event = attribute(HTML::AttributeNames::event).trim_whitespace();
  158. if (!for_.equals_ignoring_case("window")) {
  159. dbgln("HTMLScriptElement: Refusing to run classic script because the provided 'for' attribute is not equal to 'window'");
  160. return;
  161. }
  162. if (!event.equals_ignoring_case("onload") && !event.equals_ignoring_case("onload()")) {
  163. dbgln("HTMLScriptElement: Refusing to run classic script because the provided 'event' attribute is not equal to 'onload' or 'onload()'");
  164. return;
  165. }
  166. }
  167. // FIXME: Check "charset" attribute
  168. // FIXME: Check CORS
  169. // FIXME: Module script credentials mode
  170. // FIXME: Cryptographic nonce
  171. // FIXME: Check "integrity" attribute
  172. // FIXME: Check "referrerpolicy" attribute
  173. m_parser_inserted = !!m_parser_document;
  174. // FIXME: Check fetch options
  175. if (has_attribute(HTML::AttributeNames::src)) {
  176. auto src = attribute(HTML::AttributeNames::src);
  177. if (src.is_empty()) {
  178. dbgln("HTMLScriptElement: Refusing to run script because the src attribute is empty.");
  179. // FIXME: Queue a task to do this.
  180. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  181. return;
  182. }
  183. m_from_an_external_file = true;
  184. auto url = document().complete_url(src);
  185. if (!url.is_valid()) {
  186. dbgln("HTMLScriptElement: Refusing to run script because the src URL '{}' is invalid.", url);
  187. // FIXME: Queue a task to do this.
  188. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  189. return;
  190. }
  191. if (m_script_type == ScriptType::Classic) {
  192. // FIXME: This load should be made asynchronous and the parser should spin an event loop etc.
  193. ResourceLoader::the().load_sync(
  194. url,
  195. [this, url](auto data, auto&) {
  196. if (data.is_null()) {
  197. dbgln("HTMLScriptElement: Failed to load {}", url);
  198. return;
  199. }
  200. m_script_source = String::copy(data);
  201. script_became_ready();
  202. },
  203. [this](auto&) {
  204. m_failed_to_load = true;
  205. });
  206. } else {
  207. TODO();
  208. }
  209. } else {
  210. if (m_script_type == ScriptType::Classic) {
  211. m_script_source = source_text;
  212. script_became_ready();
  213. } else {
  214. TODO();
  215. }
  216. }
  217. if ((m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::src) && has_attribute(HTML::AttributeNames::defer) && m_parser_inserted && !has_attribute(HTML::AttributeNames::async))
  218. || (m_script_type == ScriptType::Module && m_parser_inserted && !has_attribute(HTML::AttributeNames::async))) {
  219. document().add_script_to_execute_when_parsing_has_finished({}, *this);
  220. when_the_script_is_ready([this] {
  221. m_ready_to_be_parser_executed = true;
  222. });
  223. }
  224. else if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::src) && m_parser_inserted && !has_attribute(HTML::AttributeNames::async)) {
  225. document().set_pending_parsing_blocking_script({}, this);
  226. when_the_script_is_ready([this] {
  227. m_ready_to_be_parser_executed = true;
  228. });
  229. }
  230. else if ((m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::src) && !has_attribute(HTML::AttributeNames::async) && !m_non_blocking)
  231. || (m_script_type == ScriptType::Module && !has_attribute(HTML::AttributeNames::async) && !m_non_blocking)) {
  232. TODO();
  233. }
  234. else if ((m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::src)) || m_script_type == ScriptType::Module) {
  235. // FIXME: This should add to a set, not a list.
  236. m_preparation_time_document->add_script_to_execute_as_soon_as_possible({}, *this);
  237. // FIXME: When the script is ready, execute the script block and then remove the element
  238. // from the set of scripts that will execute as soon as possible.
  239. }
  240. // FIXME: If the element does not have a src attribute, and the element is "parser-inserted",
  241. // and either the parser that created the script is an XML parser or it's an HTML parser
  242. // whose script nesting level is not greater than one, and the element's parser document
  243. // has a style sheet that is blocking scripts:
  244. // The element is the pending parsing-blocking script of its parser document.
  245. // (There can only be one such script per Document at a time.)
  246. // Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
  247. else {
  248. // Immediately execute the script block, even if other scripts are already executing.
  249. execute_script();
  250. }
  251. }
  252. void HTMLScriptElement::script_became_ready()
  253. {
  254. m_script_ready = true;
  255. if (!m_script_ready_callback)
  256. return;
  257. m_script_ready_callback();
  258. m_script_ready_callback = nullptr;
  259. }
  260. void HTMLScriptElement::when_the_script_is_ready(Function<void()> callback)
  261. {
  262. if (m_script_ready) {
  263. callback();
  264. return;
  265. }
  266. m_script_ready_callback = move(callback);
  267. }
  268. }