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, 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& string)
  93. {
  94. auto lowercase_string = string.to_lowercase();
  95. return lowercase_string.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");
  96. }
  97. // https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
  98. void HTMLScriptElement::prepare_script(Badge<HTMLDocumentParser>)
  99. {
  100. if (m_already_started) {
  101. dbgln("HTMLScriptElement: Refusing to run script because it has already started.");
  102. return;
  103. }
  104. RefPtr<DOM::Document> parser_document = m_parser_document.ptr();
  105. m_parser_document = nullptr;
  106. if (parser_document && !has_attribute(HTML::AttributeNames::async)) {
  107. m_non_blocking = true;
  108. }
  109. auto source_text = child_text_content();
  110. if (!has_attribute(HTML::AttributeNames::src) && source_text.is_empty()) {
  111. dbgln("HTMLScriptElement: Refusing to run empty script.");
  112. return;
  113. }
  114. if (!is_connected()) {
  115. dbgln("HTMLScriptElement: Refusing to run script because the element is not connected.");
  116. return;
  117. }
  118. String script_block_type;
  119. bool has_type = has_attribute(HTML::AttributeNames::type);
  120. bool has_language = has_attribute(HTML::AttributeNames::language);
  121. if ((has_type && attribute(HTML::AttributeNames::type).is_empty())
  122. || (!has_type && has_language && attribute(HTML::AttributeNames::language).is_empty())
  123. || (!has_type && !has_language)) {
  124. script_block_type = "text/javascript";
  125. } else if (has_type) {
  126. script_block_type = attribute(HTML::AttributeNames::type).trim_whitespace();
  127. } else if (!attribute(HTML::AttributeNames::language).is_empty()) {
  128. script_block_type = String::formatted("text/{}", attribute(HTML::AttributeNames::language));
  129. }
  130. if (is_javascript_mime_type_essence_match(script_block_type)) {
  131. m_script_type = ScriptType::Classic;
  132. } else if (script_block_type.equals_ignoring_case("module")) {
  133. m_script_type = ScriptType::Module;
  134. } else {
  135. dbgln("HTMLScriptElement: Refusing to run script because the type '{}' is not recognized.", script_block_type);
  136. return;
  137. }
  138. if (parser_document) {
  139. m_parser_document = *parser_document;
  140. m_non_blocking = false;
  141. }
  142. m_already_started = true;
  143. m_preparation_time_document = document();
  144. if (parser_document && parser_document.ptr() != m_preparation_time_document.ptr()) {
  145. dbgln("HTMLScriptElement: Refusing to run script because the parser document is not the same as the preparation time document.");
  146. return;
  147. }
  148. // FIXME: Check if scripting is disabled, if so return
  149. if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::nomodule)) {
  150. dbgln("HTMLScriptElement: Refusing to run classic script because it has the nomodule attribute.");
  151. return;
  152. }
  153. // FIXME: Check CSP
  154. if (m_script_type == ScriptType::Classic && has_attribute(HTML::AttributeNames::event) && has_attribute(HTML::AttributeNames::for_)) {
  155. auto for_ = attribute(HTML::AttributeNames::for_).trim_whitespace();
  156. auto event = attribute(HTML::AttributeNames::event).trim_whitespace();
  157. if (!for_.equals_ignoring_case("window")) {
  158. dbgln("HTMLScriptElement: Refusing to run classic script because the provided 'for' attribute is not equal to 'window'");
  159. return;
  160. }
  161. if (!event.equals_ignoring_case("onload") && !event.equals_ignoring_case("onload()")) {
  162. dbgln("HTMLScriptElement: Refusing to run classic script because the provided 'event' attribute is not equal to 'onload' or 'onload()'");
  163. return;
  164. }
  165. }
  166. // FIXME: Check "charset" attribute
  167. // FIXME: Check CORS
  168. // FIXME: Module script credentials mode
  169. // FIXME: Cryptographic nonce
  170. // FIXME: Check "integrity" attribute
  171. // FIXME: Check "referrerpolicy" attribute
  172. m_parser_inserted = !!m_parser_document;
  173. // FIXME: Check fetch options
  174. if (has_attribute(HTML::AttributeNames::src)) {
  175. auto src = attribute(HTML::AttributeNames::src);
  176. if (src.is_empty()) {
  177. dbgln("HTMLScriptElement: Refusing to run script because the src attribute is empty.");
  178. // FIXME: Queue a task to do this.
  179. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  180. return;
  181. }
  182. m_from_an_external_file = true;
  183. auto url = document().complete_url(src);
  184. if (!url.is_valid()) {
  185. dbgln("HTMLScriptElement: Refusing to run script because the src URL '{}' is invalid.", url);
  186. // FIXME: Queue a task to do this.
  187. dispatch_event(DOM::Event::create(HTML::EventNames::error));
  188. return;
  189. }
  190. if (m_script_type == ScriptType::Classic) {
  191. // FIXME: This load should be made asynchronous and the parser should spin an event loop etc.
  192. m_script_filename = url.basename();
  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. }