ScriptTrace.cpp (2844B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "ScriptTrace.h" 8 9 #include "mozilla/Services.h" // services::* 10 #include "mozilla/dom/Element.h" // mozilla::dom::Element 11 #include "mozilla/dom/ScriptLoadContext.h" // mozilla::dom::ScriptLoadContext 12 #include "nsCOMPtr.h" // nsCOMPtr.h 13 #include "nsIObserverService.h" // nsIObserverService 14 #include "nsIScriptElement.h" // nsIScriptElement 15 #include "nsThreadUtils.h" // mozilla::Runnable, NS_DispatchToCurrentThread 16 17 namespace mozilla::dom::script { 18 19 class ScriptLoaderTestRunnable : public Runnable { 20 public: 21 ScriptLoaderTestRunnable(JS::loader::ScriptLoadRequest* aRequest, 22 JS::loader::LoadedScript* aLoadedScript, 23 const char* aEvent) 24 : Runnable("dom::script::ScriptLoaderTestRunnable") { 25 mData.AppendLiteral(u"event:"); 26 mData.AppendASCII(aEvent); 27 if (aLoadedScript) { 28 mData.AppendLiteral(u"\nurl:"); 29 mData.Append( 30 NS_ConvertUTF8toUTF16(aLoadedScript->GetURI()->GetSpecOrDefault())); 31 } 32 33 if (aRequest) { 34 nsIScriptElement* scriptElement = 35 aRequest->GetScriptLoadContext()->GetScriptElementForTrace(); 36 nsCOMPtr<Element> target(do_QueryInterface(scriptElement)); 37 if (target) { 38 nsAutoString id; 39 target->GetId(id); 40 mData.AppendLiteral(u"\nid:"); 41 mData.Append(id); 42 } 43 } 44 } 45 46 NS_IMETHOD Run() override { 47 nsCOMPtr<nsIObserverService> obsService = services::GetObserverService(); 48 obsService->NotifyObservers(nullptr, "ScriptLoaderTest", 49 mData.BeginReading()); 50 return NS_OK; 51 } 52 53 protected: 54 ~ScriptLoaderTestRunnable() = default; 55 56 private: 57 nsAutoString mData; 58 }; 59 60 void TestingNotifyObserver(JS::loader::ScriptLoadRequest* aRequest, 61 JS::loader::LoadedScript* aLoadedScript, 62 const char* aEvent) { 63 nsCOMPtr<nsIObserverService> obsService = services::GetObserverService(); 64 65 if (!obsService->HasObservers("ScriptLoaderTest")) { 66 return; 67 } 68 69 // NOTE: There can be pending exception for the script load itself, 70 // and the observer notification shouldn't be performed in that 71 // situation. 72 // Use a separate task to avoid the collision. 73 RefPtr<ScriptLoaderTestRunnable> runnable = 74 new ScriptLoaderTestRunnable(aRequest, aLoadedScript, aEvent); 75 (void)NS_DispatchToCurrentThread(runnable); 76 } 77 78 } // namespace mozilla::dom::script