1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "config.h" 6 #include "modules/serviceworkers/NavigatorServiceWorker.h" 7 8 #include "core/dom/Document.h" 9 #include "core/frame/LocalDOMWindow.h" 10 #include "core/frame/LocalFrame.h" 11 #include "core/frame/Navigator.h" 12 #include "modules/serviceworkers/ServiceWorkerContainer.h" 13 14 namespace blink { 15 16 NavigatorServiceWorker::NavigatorServiceWorker(Navigator& navigator) 17 : DOMWindowProperty(navigator.frame()) 18 { 19 } 20 21 DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(NavigatorServiceWorker); 22 23 NavigatorServiceWorker* NavigatorServiceWorker::from(Document& document) 24 { 25 if (!document.frame() || !document.frame()->domWindow()) 26 return 0; 27 Navigator& navigator = document.frame()->domWindow()->navigator(); 28 return &from(navigator); 29 } 30 31 NavigatorServiceWorker& NavigatorServiceWorker::from(Navigator& navigator) 32 { 33 NavigatorServiceWorker* supplement = toNavigatorServiceWorker(navigator); 34 if (!supplement) { 35 supplement = new NavigatorServiceWorker(navigator); 36 provideTo(navigator, supplementName(), adoptPtrWillBeNoop(supplement)); 37 // Initialize ServiceWorkerContainer too. 38 supplement->serviceWorker(); 39 } 40 return *supplement; 41 } 42 43 NavigatorServiceWorker* NavigatorServiceWorker::toNavigatorServiceWorker(Navigator& navigator) 44 { 45 return static_cast<NavigatorServiceWorker*>(WillBeHeapSupplement<Navigator>::from(navigator, supplementName())); 46 } 47 48 const char* NavigatorServiceWorker::supplementName() 49 { 50 return "NavigatorServiceWorker"; 51 } 52 53 ServiceWorkerContainer* NavigatorServiceWorker::serviceWorker(Navigator& navigator) 54 { 55 return NavigatorServiceWorker::from(navigator).serviceWorker(); 56 } 57 58 ServiceWorkerContainer* NavigatorServiceWorker::serviceWorker() 59 { 60 if (!m_serviceWorker && frame()) { 61 ASSERT(frame()->domWindow()); 62 m_serviceWorker = ServiceWorkerContainer::create(frame()->domWindow()->executionContext()); 63 } 64 return m_serviceWorker.get(); 65 } 66 67 void NavigatorServiceWorker::willDetachGlobalObjectFromFrame() 68 { 69 if (m_serviceWorker) { 70 m_serviceWorker->willBeDetachedFromFrame(); 71 m_serviceWorker = nullptr; 72 } 73 } 74 75 void NavigatorServiceWorker::trace(Visitor* visitor) 76 { 77 visitor->trace(m_serviceWorker); 78 WillBeHeapSupplement<Navigator>::trace(visitor); 79 DOMWindowProperty::trace(visitor); 80 } 81 82 } // namespace blink 83