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 "extensions/browser/shared_user_script_master.h"
6
7 #include "extensions/browser/extension_util.h"
8 #include "extensions/common/host_id.h"
9 #include "extensions/common/manifest_handlers/content_scripts_handler.h"
10
11 namespace extensions {
12
SharedUserScriptMaster(content::BrowserContext * browser_context)13 SharedUserScriptMaster::SharedUserScriptMaster(
14 content::BrowserContext* browser_context)
15 : loader_(browser_context,
16 HostID(),
17 true /* listen_for_extension_system_loaded */),
18 browser_context_(browser_context) {
19 extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_));
20 }
21
~SharedUserScriptMaster()22 SharedUserScriptMaster::~SharedUserScriptMaster() {}
23
OnExtensionLoaded(content::BrowserContext * browser_context,const Extension * extension)24 void SharedUserScriptMaster::OnExtensionLoaded(
25 content::BrowserContext* browser_context,
26 const Extension* extension) {
27 loader_.AddScripts(GetScriptsMetadata(extension));
28 }
29
OnExtensionUnloaded(content::BrowserContext * browser_context,const Extension * extension,UnloadedExtensionReason reason)30 void SharedUserScriptMaster::OnExtensionUnloaded(
31 content::BrowserContext* browser_context,
32 const Extension* extension,
33 UnloadedExtensionReason reason) {
34 const UserScriptList& script_list =
35 ContentScriptsInfo::GetContentScripts(extension);
36 std::set<UserScriptIDPair> scripts_to_remove;
37 for (const std::unique_ptr<UserScript>& script : script_list)
38 scripts_to_remove.insert(UserScriptIDPair(script->id(), script->host_id()));
39 loader_.RemoveScripts(scripts_to_remove);
40 }
41
GetScriptsMetadata(const Extension * extension)42 std::unique_ptr<UserScriptList> SharedUserScriptMaster::GetScriptsMetadata(
43 const Extension* extension) {
44 bool incognito_enabled =
45 util::IsIncognitoEnabled(extension->id(), browser_context_);
46 const UserScriptList& script_list =
47 ContentScriptsInfo::GetContentScripts(extension);
48 std::unique_ptr<UserScriptList> script_vector(new UserScriptList());
49 script_vector->reserve(script_list.size());
50 for (const std::unique_ptr<UserScript>& script : script_list) {
51 std::unique_ptr<UserScript> script_copy =
52 UserScript::CopyMetadataFrom(*script);
53 script_copy->set_incognito_enabled(incognito_enabled);
54 script_vector->push_back(std::move(script_copy));
55 }
56 return script_vector;
57 }
58
59 } // namespace extensions
60