HTMLScriptElement.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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, QualifiedName qualified_name)
  39. : HTMLElement(document, move(qualified_name))
  40. , m_script_filename("(document)")
  41. {
  42. }
  43. HTMLScriptElement::~HTMLScriptElement()
  44. {
  45. }
  46. void HTMLScriptElement::set_parser_document(Badge<HTMLDocumentParser>, DOM::Document& document)
  47. {
  48. m_parser_document = document;
  49. }
  50. void HTMLScriptElement::set_non_blocking(Badge<HTMLDocumentParser>, bool non_blocking)
  51. {
  52. m_non_blocking = non_blocking;
  53. }
  54. void HTMLScriptElement::execute_script()
  55. {
  56. if (m_preparation_time_document.ptr() != &document()) {
  57. dbgln("HTMLScriptElement: Refusing to run script because the preparation time document is not the same as the node document.");
  58. return;
  59. }
  60. if (m_script_source.is_null()) {
  61. dbgln("HTMLScriptElement: Refusing to run script because the script source is null.");
  62. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  63. return;
  64. }
  65. bool incremented_destructive_writes_counter = false;
  66. if (m_from_an_external_file || m_script_type == ScriptType::Module) {
  67. document().increment_ignore_destructive_writes_counter();
  68. incremented_destructive_writes_counter = true;
  69. }
  70. if (m_script_type == ScriptType::Classic) {
  71. auto old_current_script = document().current_script();
  72. if (!is<DOM::ShadowRoot>(root()))
  73. document().set_current_script({}, this);
  74. else
  75. document().set_current_script({}, nullptr);
  76. if (m_from_an_external_file)
  77. dbgln_if(HTML_SCRIPT_DEBUG, "HTMLScriptElement: Running script {}", attribute(HTML::AttributeNames::src));
  78. else
  79. dbgln_if(HTML_SCRIPT_DEBUG, "HTMLScriptElement: Running inline script");
  80. document().run_javascript(m_script_source, m_script_filename);
  81. document().set_current_script({}, old_current_script);
  82. } else {
  83. VERIFY(!document().current_script());
  84. TODO();
  85. }
  86. if (incremented_destructive_writes_counter)
  87. document().decrement_ignore_destructive_writes_counter();
  88. if (m_from_an_external_file)
  89. dispatch_event(DOM::Event::create(HTML::EventNames::load));
  90. }
  91. // https://mimesniff.spec.whatwg.org/#javascript-mime-type-essence-match
  92. static bool is_javascript_mime_type_essence_match(const String& mime_type)
  93. {
  94. // FIXME: This operates on the whole mime type, instead of just the essence. https://mimesniff.spec.whatwg.org/#mime-type-essence
  95. // It'd probably be best to make a helper class for mime types, since there is a whole spec about mime types.
  96. auto lowercase_mime_type = mime_type.to_lowercase();
  97. 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");
  98. }
  99. // https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
  100. void HTMLScriptElement::prepare_script(Badge<HTMLDocumentParser>)
  101. {
  102. if (m_already_started) {
  103. dbgln("HTMLScriptElement: Refusing to run script because it has already started.");
  104. return;
  105. }
  106. RefPtr<DOM::Document> parser_document = m_parser_document.ptr();
  107. m_parser_document = nullptr;
  108. if (parser_document && !has_attribute(HTML::AttributeNames::async)) {
  109. m_non_blocking = true;
  110. }
  111. auto source_text = child_text_content();
  112. if (!has_attribute(HTML::AttributeNames::src) && source_text.is_empty()) {
  113. dbgln("HTMLScriptElement: Refusing to run empty script.");
  114. return;
  115. }
  116. if (!is_connected()) {
  117. dbgln("HTMLScriptElement: Refusing to run script because the element is not connected.");
  118. return;
  119. }
  120. String script_block_type;
  121. bool has_type = has_attribute(HTML::AttributeNames::type);
  122. bool has_language = has_attribute(HTML::AttributeNames::language);
  123. if ((has_type && attribute(HTML::AttributeNames::type).is_empty())
  124. || (!has_type && has_language && attribute(HTML::AttributeNames::language).is_empty())
  125. || (!has_type && !has_language)) {
  126. script_block_type = "text/javascript";
  127. } else if (has_type) {
  128. script_block_type = attribute(HTML::AttributeNames::type).trim_whitespace();
  129. } else if (!attribute(HTML::AttributeNames::language).is_empty()) {
  130. script_block_type = String::formatted("text/{}", attribute(HTML::AttributeNames::language));
  131. }
  132. if (is_javascript_mime_type_essence_match(script_block_type)) {
  133. m_script_type = ScriptType::Classic;
  134. } else if (script_block_type.equals_ignoring_case("module")) {
  135. m_script_type = ScriptType::Module;
  136. } else {
  137. dbgln("HTMLScriptElement: Refusing to run script because the type '{}' is not recognized.", script_block_type);
  138. return;
  139. }
  140. if (parser_document) {
  141. m_parser_document = *parser_document;
  142. m_non_blocking = false;
  143. }
  144. m_already_started = true;
  145. m_preparation_time_document = document();
  146. if (parser_document && parser_document.ptr() != m_preparation_time_document.ptr()) {
  147. dbgln("HTMLScriptElement: Refusing to run script because the parser document is not the same as the preparation time document.");
  148. return;
  149. }
  150. // FIXME: Check if scripting is disabled, if so return
  151. if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::nomodule)) {
  152. dbgln("HTMLScriptElement: Refusing to run classic script because it has the nomodule attribute.");
  153. return;
  154. }
  155. // FIXME: Check CSP
  156. if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::event) && has_attribute(HTML::AttributeNames::for_)) {
  157. auto for_ = attribute(HTML::AttributeNames::for_).trim_whitespace();
  158. auto event = attribute(HTML::AttributeNames::event).trim_whitespace();
  159. if (!for_.equals_ignoring_case("window")) {
  160. dbgln("HTMLScriptElement: Refusing to run classic script because the provided 'for' attribute is not equal to 'window'");
  161. return;
  162. }
  163. if (!event.equals_ignoring_case("onload") && !event.equals_ignoring_case("onload()")) {
  164. dbgln("HTMLScriptElement: Refusing to run classic script because the provided 'event' attribute is not equal to 'onload' or 'onload()'");
  165. return;
  166. }
  167. }
  168. // FIXME: Check "charset" attribute
  169. // FIXME: Check CORS
  170. // FIXME: Module script credentials mode
  171. // FIXME: Cryptographic nonce
  172. // FIXME: Check "integrity" attribute
  173. // FIXME: Check "referrerpolicy" attribute
  174. m_parser_inserted = !!m_parser_document;
  175. // FIXME: Check fetch options
  176. if (has_attribute(HTML::AttributeNames::src)) {
  177. auto src = attribute(HTML::AttributeNames::src);
  178. if (src.is_empty()) {
  179. dbgln("HTMLScriptElement: Refusing to run script because the src attribute is empty.");
  180. // FIXME: Queue a task to do this.
  181. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  182. return;
  183. }
  184. m_from_an_external_file = true;
  185. auto url = document().complete_url(src);
  186. if (!url.is_valid()) {
  187. dbgln("HTMLScriptElement: Refusing to run script because the src URL '{}' is invalid.", url);
  188. // FIXME: Queue a task to do this.
  189. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  190. return;
  191. }
  192. if (m_script_type == ScriptType::Classic) {
  193. // FIXME: This load should be made asynchronous and the parser should spin an event loop etc.
  194. m_script_filename = url.basename();
  195. ResourceLoader::the().load_sync(
  196. url,
  197. [this, url](auto data, auto&) {
  198. if (data.is_null()) {
  199. dbgln("HTMLScriptElement: Failed to load {}", url);
  200. return;
  201. }
  202. m_script_source = String::copy(data);
  203. script_became_ready();
  204. },
  205. [this](auto&) {
  206. m_failed_to_load = true;
  207. });
  208. } else {
  209. TODO();
  210. }
  211. } else {
  212. if (m_script_type == ScriptType::Classic) {
  213. m_script_source = source_text;
  214. script_became_ready();
  215. } else {
  216. TODO();
  217. }
  218. }
  219. if ((m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::src) && has_attribute(HTML::AttributeNames::defer) && m_parser_inserted && !has_attribute(HTML::AttributeNames::async))
  220. || (m_script_type == ScriptType::Module && m_parser_inserted && !has_attribute(HTML::AttributeNames::async))) {
  221. document().add_script_to_execute_when_parsing_has_finished({}, *this);
  222. when_the_script_is_ready([this] {
  223. m_ready_to_be_parser_executed = true;
  224. });
  225. }
  226. else if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::src) && m_parser_inserted && !has_attribute(HTML::AttributeNames::async)) {
  227. document().set_pending_parsing_blocking_script({}, this);
  228. when_the_script_is_ready([this] {
  229. m_ready_to_be_parser_executed = true;
  230. });
  231. }
  232. else if ((m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::src) && !has_attribute(HTML::AttributeNames::async) && !m_non_blocking)
  233. || (m_script_type == ScriptType::Module && !has_attribute(HTML::AttributeNames::async) && !m_non_blocking)) {
  234. TODO();
  235. }
  236. else if ((m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::src)) || m_script_type == ScriptType::Module) {
  237. // FIXME: This should add to a set, not a list.
  238. m_preparation_time_document->add_script_to_execute_as_soon_as_possible({}, *this);
  239. // FIXME: When the script is ready, execute the script block and then remove the element
  240. // from the set of scripts that will execute as soon as possible.
  241. }
  242. // FIXME: If the element does not have a src attribute, and the element is "parser-inserted",
  243. // and either the parser that created the script is an XML parser or it's an HTML parser
  244. // whose script nesting level is not greater than one, and the element's parser document
  245. // has a style sheet that is blocking scripts:
  246. // The element is the pending parsing-blocking script of its parser document.
  247. // (There can only be one such script per Document at a time.)
  248. // Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
  249. else {
  250. // Immediately execute the script block, even if other scripts are already executing.
  251. execute_script();
  252. }
  253. }
  254. void HTMLScriptElement::script_became_ready()
  255. {
  256. m_script_ready = true;
  257. if (!m_script_ready_callback)
  258. return;
  259. m_script_ready_callback();
  260. m_script_ready_callback = nullptr;
  261. }
  262. void HTMLScriptElement::when_the_script_is_ready(Function<void()> callback)
  263. {
  264. if (m_script_ready) {
  265. callback();
  266. return;
  267. }
  268. m_script_ready_callback = move(callback);
  269. }
  270. }