feat: [extensions] implement a couple of tabs APIs (#21779)

This commit is contained in:
Jeremy Apthorp 2020-01-15 15:11:51 -08:00 коммит произвёл GitHub
Родитель 8278a64e00
Коммит b9eb68c0b4
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
21 изменённых файлов: 568 добавлений и 17 удалений

Просмотреть файл

@ -664,7 +664,8 @@ source_set("electron_lib") {
]
}
public_deps += [ "shell/common/extensions/api:extensions_features" ]
deps += [ "shell/common/extensions/api:extensions_features" ]
deps += [ "shell/common/extensions/api" ]
deps += [
"//components/pref_registry",
"//components/user_prefs",

Просмотреть файл

@ -229,6 +229,13 @@ static_library("chrome") {
"//components/vector_icons:vector_icons",
]
}
if (enable_electron_extensions) {
sources += [
"//chrome/renderer/extensions/tabs_hooks_delegate.cc",
"//chrome/renderer/extensions/tabs_hooks_delegate.h",
]
}
}
source_set("plugins") {

Просмотреть файл

@ -591,6 +591,8 @@ filenames = {
lib_sources_extensions = [
"shell/browser/extensions/api/runtime/atom_runtime_api_delegate.cc",
"shell/browser/extensions/api/runtime/atom_runtime_api_delegate.h",
"shell/browser/extensions/api/tabs/tabs_api.cc",
"shell/browser/extensions/api/tabs/tabs_api.h",
"shell/browser/extensions/atom_extensions_browser_client.cc",
"shell/browser/extensions/atom_extensions_browser_client.h",
"shell/browser/extensions/atom_browser_context_keyed_service_factories.cc",
@ -613,6 +615,8 @@ filenames = {
"shell/browser/extensions/electron_process_manager_delegate.h",
"shell/browser/extensions/electron_extensions_api_client.cc",
"shell/browser/extensions/electron_extensions_api_client.h",
"shell/browser/extensions/electron_extensions_browser_api_provider.cc",
"shell/browser/extensions/electron_extensions_browser_api_provider.h",
"shell/browser/extensions/electron_messaging_delegate.cc",
"shell/browser/extensions/electron_messaging_delegate.h",
"shell/common/extensions/atom_extensions_api_provider.cc",
@ -621,6 +625,8 @@ filenames = {
"shell/common/extensions/atom_extensions_client.h",
"shell/renderer/extensions/atom_extensions_renderer_client.cc",
"shell/renderer/extensions/atom_extensions_renderer_client.h",
"shell/renderer/extensions/electron_extensions_dispatcher_delegate.cc",
"shell/renderer/extensions/electron_extensions_dispatcher_delegate.h",
]
app_sources = [

Просмотреть файл

@ -361,6 +361,7 @@ WebContents::WebContents(v8::Isolate* isolate,
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::AtomExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_.reset(new extensions::ScriptExecutor(web_contents));
#endif
registry_.AddInterface(base::BindRepeating(&WebContents::BindElectronBrowser,
base::Unretained(this)));
@ -521,6 +522,7 @@ void WebContents::InitWithSessionAndOptions(
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::AtomExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_.reset(new extensions::ScriptExecutor(web_contents()));
#endif
registry_.AddInterface(base::BindRepeating(&WebContents::BindElectronBrowser,

Просмотреть файл

@ -36,6 +36,10 @@
#include "shell/browser/printing/print_preview_message_handler.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#endif
namespace blink {
struct WebDeviceEmulationParams;
}
@ -327,6 +331,12 @@ class WebContents : public gin_helper::TrackableObject<WebContents>,
WebContents* embedder() { return embedder_; }
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ScriptExecutor* script_executor() {
return script_executor_.get();
}
#endif
protected:
// Does not manage lifetime of |web_contents|.
WebContents(v8::Isolate* isolate, content::WebContents* web_contents);
@ -537,6 +547,10 @@ class WebContents : public gin_helper::TrackableObject<WebContents>,
std::unique_ptr<WebViewGuestDelegate> guest_delegate_;
std::unique_ptr<FrameSubscriber> frame_subscriber_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
std::unique_ptr<extensions::ScriptExecutor> script_executor_;
#endif
// The host webcontents that may contain this webcontents.
WebContents* embedder_ = nullptr;

Просмотреть файл

@ -0,0 +1,133 @@
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/extensions/api/tabs/tabs_api.h"
#include <memory>
#include <utility>
#include "extensions/browser/extension_api_frame_id_map.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/permissions/permissions_data.h"
#include "shell/browser/api/atom_api_web_contents.h"
namespace extensions {
const char kFrameNotFoundError[] = "No frame with id * in tab *.";
using api::extension_types::InjectDetails;
ExecuteCodeInTabFunction::ExecuteCodeInTabFunction() : execute_tab_id_(-1) {}
ExecuteCodeInTabFunction::~ExecuteCodeInTabFunction() {}
ExecuteCodeFunction::InitResult ExecuteCodeInTabFunction::Init() {
if (init_result_)
return init_result_.value();
// |tab_id| is optional so it's ok if it's not there.
int tab_id = -1;
if (args_->GetInteger(0, &tab_id) && tab_id < 0)
return set_init_result(VALIDATION_FAILURE);
// |details| are not optional.
base::DictionaryValue* details_value = NULL;
if (!args_->GetDictionary(1, &details_value))
return set_init_result(VALIDATION_FAILURE);
std::unique_ptr<InjectDetails> details(new InjectDetails());
if (!InjectDetails::Populate(*details_value, details.get()))
return set_init_result(VALIDATION_FAILURE);
if (tab_id == -1) {
// There's no useful concept of a "default tab" in Electron.
// TODO(nornagon): we could potentially kick this to an event to allow the
// app to decide what "default tab" means for them?
return set_init_result(VALIDATION_FAILURE);
}
execute_tab_id_ = tab_id;
details_ = std::move(details);
set_host_id(HostID(HostID::EXTENSIONS, extension()->id()));
return set_init_result(SUCCESS);
}
bool ExecuteCodeInTabFunction::CanExecuteScriptOnPage(std::string* error) {
// If |tab_id| is specified, look for the tab. Otherwise default to selected
// tab in the current window.
CHECK_GE(execute_tab_id_, 0);
auto* contents = electron::api::WebContents::FromWeakMapID(
v8::Isolate::GetCurrent(), execute_tab_id_);
if (!contents) {
return false;
}
int frame_id = details_->frame_id ? *details_->frame_id
: ExtensionApiFrameIdMap::kTopFrameId;
content::RenderFrameHost* rfh =
ExtensionApiFrameIdMap::GetRenderFrameHostById(contents->web_contents(),
frame_id);
if (!rfh) {
*error = ErrorUtils::FormatErrorMessage(
kFrameNotFoundError, base::NumberToString(frame_id),
base::NumberToString(execute_tab_id_));
return false;
}
// Content scripts declared in manifest.json can access frames at about:-URLs
// if the extension has permission to access the frame's origin, so also allow
// programmatic content scripts at about:-URLs for allowed origins.
GURL effective_document_url(rfh->GetLastCommittedURL());
bool is_about_url = effective_document_url.SchemeIs(url::kAboutScheme);
if (is_about_url && details_->match_about_blank &&
*details_->match_about_blank) {
effective_document_url = GURL(rfh->GetLastCommittedOrigin().Serialize());
}
if (!effective_document_url.is_valid()) {
// Unknown URL, e.g. because no load was committed yet. Allow for now, the
// renderer will check again and fail the injection if needed.
return true;
}
// NOTE: This can give the wrong answer due to race conditions, but it is OK,
// we check again in the renderer.
if (!extension()->permissions_data()->CanAccessPage(effective_document_url,
execute_tab_id_, error)) {
if (is_about_url &&
extension()->permissions_data()->active_permissions().HasAPIPermission(
APIPermission::kTab)) {
*error = ErrorUtils::FormatErrorMessage(
manifest_errors::kCannotAccessAboutUrl,
rfh->GetLastCommittedURL().spec(),
rfh->GetLastCommittedOrigin().Serialize());
}
return false;
}
return true;
}
ScriptExecutor* ExecuteCodeInTabFunction::GetScriptExecutor(
std::string* error) {
auto* contents = electron::api::WebContents::FromWeakMapID(
v8::Isolate::GetCurrent(), execute_tab_id_);
if (!contents)
return nullptr;
return contents->script_executor();
}
bool ExecuteCodeInTabFunction::IsWebView() const {
return false;
}
const GURL& ExecuteCodeInTabFunction::GetWebViewSrc() const {
return GURL::EmptyGURL();
}
bool TabsExecuteScriptFunction::ShouldInsertCSS() const {
return false;
}
} // namespace extensions

Просмотреть файл

@ -0,0 +1,49 @@
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef SHELL_BROWSER_EXTENSIONS_API_TABS_TABS_API_H_
#define SHELL_BROWSER_EXTENSIONS_API_TABS_TABS_API_H_
#include <string>
#include "extensions/browser/api/execute_code_function.h"
#include "extensions/browser/extension_function.h"
#include "extensions/common/extension_resource.h"
#include "url/gurl.h"
namespace extensions {
// Implement API call tabs.executeScript and tabs.insertCSS.
class ExecuteCodeInTabFunction : public ExecuteCodeFunction {
public:
ExecuteCodeInTabFunction();
protected:
~ExecuteCodeInTabFunction() override;
// Initializes |execute_tab_id_| and |details_|.
InitResult Init() override;
bool CanExecuteScriptOnPage(std::string* error) override;
ScriptExecutor* GetScriptExecutor(std::string* error) override;
bool IsWebView() const override;
const GURL& GetWebViewSrc() const override;
private:
// Id of tab which executes code.
int execute_tab_id_;
};
class TabsExecuteScriptFunction : public ExecuteCodeInTabFunction {
protected:
bool ShouldInsertCSS() const override;
private:
~TabsExecuteScriptFunction() override {}
DECLARE_EXTENSION_FUNCTION("tabs.executeScript", TABS_EXECUTESCRIPT)
};
} // namespace extensions
#endif // SHELL_BROWSER_EXTENSIONS_API_TABS_TABS_API_H_

Просмотреть файл

@ -36,6 +36,7 @@
#include "shell/browser/extensions/atom_extension_web_contents_observer.h"
#include "shell/browser/extensions/atom_navigation_ui_data.h"
#include "shell/browser/extensions/electron_extensions_api_client.h"
#include "shell/browser/extensions/electron_extensions_browser_api_provider.h"
#include "shell/browser/extensions/electron_process_manager_delegate.h"
using content::BrowserContext;
@ -53,7 +54,8 @@ AtomExtensionsBrowserClient::AtomExtensionsBrowserClient()
AddAPIProvider(
std::make_unique<extensions::CoreExtensionsBrowserAPIProvider>());
// AddAPIProvider(std::make_unique<AtomExtensionsBrowserAPIProvider>());
AddAPIProvider(
std::make_unique<extensions::ElectronExtensionsBrowserAPIProvider>());
}
AtomExtensionsBrowserClient::~AtomExtensionsBrowserClient() {}

Просмотреть файл

@ -0,0 +1,26 @@
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/extensions/electron_extensions_browser_api_provider.h"
#include "extensions/browser/extension_function_registry.h"
#include "shell/browser/extensions/api/tabs/tabs_api.h"
namespace extensions {
ElectronExtensionsBrowserAPIProvider::ElectronExtensionsBrowserAPIProvider() =
default;
ElectronExtensionsBrowserAPIProvider::~ElectronExtensionsBrowserAPIProvider() =
default;
void ElectronExtensionsBrowserAPIProvider::RegisterExtensionFunctions(
ExtensionFunctionRegistry* registry) {
registry->RegisterFunction<TabsExecuteScriptFunction>();
/*
// Generated APIs from Electron.
api::ElectronGeneratedFunctionRegistry::RegisterAll(registry);
*/
}
} // namespace extensions

Просмотреть файл

@ -0,0 +1,27 @@
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef SHELL_BROWSER_EXTENSIONS_ELECTRON_EXTENSIONS_BROWSER_API_PROVIDER_H_
#define SHELL_BROWSER_EXTENSIONS_ELECTRON_EXTENSIONS_BROWSER_API_PROVIDER_H_
#include "base/macros.h"
#include "extensions/browser/extensions_browser_api_provider.h"
namespace extensions {
class ElectronExtensionsBrowserAPIProvider
: public ExtensionsBrowserAPIProvider {
public:
ElectronExtensionsBrowserAPIProvider();
~ElectronExtensionsBrowserAPIProvider() override;
void RegisterExtensionFunctions(ExtensionFunctionRegistry* registry) override;
private:
DISALLOW_COPY_AND_ASSIGN(ElectronExtensionsBrowserAPIProvider);
};
} // namespace extensions
#endif // SHELL_BROWSER_EXTENSIONS_ELECTRON_EXTENSIONS_BROWSER_API_PROVIDER_H_

Просмотреть файл

@ -23,6 +23,8 @@
#include "ui/gfx/native_widget_types.h"
#include "url/gurl.h"
#include "shell/browser/api/atom_api_web_contents.h"
namespace extensions {
ElectronMessagingDelegate::ElectronMessagingDelegate() = default;
@ -39,13 +41,28 @@ ElectronMessagingDelegate::IsNativeMessagingHostAllowed(
std::unique_ptr<base::DictionaryValue>
ElectronMessagingDelegate::MaybeGetTabInfo(content::WebContents* web_contents) {
if (web_contents) {
auto* api_contents = electron::api::WebContents::FromWrappedClass(
v8::Isolate::GetCurrent(), web_contents);
if (api_contents) {
auto tab = std::make_unique<base::DictionaryValue>();
tab->SetWithoutPathExpansion(
"id", std::make_unique<base::Value>(api_contents->ID()));
return tab;
}
}
return nullptr;
}
content::WebContents* ElectronMessagingDelegate::GetWebContentsByTabId(
content::BrowserContext* browser_context,
int tab_id) {
return nullptr;
auto* contents = electron::api::WebContents::FromWeakMapID(
v8::Isolate::GetCurrent(), tab_id);
if (!contents) {
return nullptr;
}
return contents->web_contents();
}
std::unique_ptr<MessagePort> ElectronMessagingDelegate::CreateReceiverForTab(

Просмотреть файл

@ -11,8 +11,16 @@ assert(enable_extensions)
################################################################################
# Public Targets
group("api") {
public_deps = [
":generated_api_json_strings",
":generated_api_types",
]
}
group("extensions_features") {
public_deps = [
":api_features",
":manifest_features",
# TODO(devlin): It would be nicer to have this dependency hoisted up to
@ -25,11 +33,52 @@ group("extensions_features") {
################################################################################
# Private Targets
generated_json_strings("generated_api_json_strings") {
sources = [
"tabs.json",
]
configs = [ "//build/config:precompiled_headers" ]
bundle_name = "Electron"
schema_include_rules = "extensions/common/api:extensions::api::%(namespace)s"
root_namespace = "extensions::api::%(namespace)s"
deps = [
"//extensions/common/api",
]
visibility = [ ":api" ]
}
generated_types("generated_api_types") {
sources = [
"tabs.json",
]
configs = [ "//build/config:precompiled_headers" ]
schema_include_rules = "extensions/common/api:extensions::api::%(namespace)s"
root_namespace = "extensions::api::%(namespace)s"
deps = [
"//extensions/common/api",
]
visibility = [ ":api" ]
}
json_features("manifest_features") {
feature_type = "ManifestFeature"
method_name = "AddAtomManifestFeatures"
method_name = "AddElectronManifestFeatures"
sources = [
"_manifest_features.json",
]
visibility = [ ":extensions_features" ]
}
json_features("api_features") {
feature_type = "APIFeature"
method_name = "AddElectronAPIFeatures"
sources = [
"_api_features.json",
]
visibility = [ ":extensions_features" ]
}

Просмотреть файл

@ -0,0 +1,7 @@
{
"tabs": {
"channel": "stable",
"extension_types": ["extension"],
"contexts": ["blessed_extension"]
}
}

Просмотреть файл

@ -0,0 +1,86 @@
[
{
"namespace": "tabs",
"functions": [
{
"name": "executeScript",
"type": "function",
"parameters": [
{
"type": "integer",
"name": "tabId",
"minimum": 0,
"optional": true,
"description": "The ID of the tab in which to run the script; defaults to the active tab of the current window."
},
{
"$ref": "extensionTypes.InjectDetails",
"name": "details",
"description": "Details of the script to run. Either the code or the file property must be set, but both may not be set at the same time."
},
{
"type": "function",
"name": "callback",
"optional": true,
"description": "Called after all the JavaScript has been executed.",
"parameters": [
{
"name": "result",
"optional": true,
"type": "array",
"items": {
"type": "any",
"minimum": 0
},
"description": "The result of the script in every injected frame."
}
]
}
]
},
{
"name": "sendMessage",
"nocompile": true,
"type": "function",
"description": "Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The $(ref:runtime.onMessage) event is fired in each content script running in the specified tab for the current extension.",
"parameters": [
{
"type": "integer",
"name": "tabId",
"minimum": 0
},
{
"type": "any",
"name": "message",
"description": "The message to send. This message should be a JSON-ifiable object."
},
{
"type": "object",
"name": "options",
"properties": {
"frameId": {
"type": "integer",
"optional": true,
"minimum": 0,
"description": "Send a message to a specific <a href='webNavigation#frame_ids'>frame</a> identified by <code>frameId</code> instead of all frames in the tab."
}
},
"optional": true
},
{
"type": "function",
"name": "responseCallback",
"optional": true,
"parameters": [
{
"name": "response",
"type": "any",
"description": "The JSON response object sent by the handler of the message. If an error occurs while connecting to the specified tab, the callback is called with no arguments and $(ref:runtime.lastError) is set to the error message."
}
]
}
]
}
]
}
]

Просмотреть файл

@ -11,13 +11,17 @@
#include "base/containers/span.h"
#include "base/strings/utf_string_conversions.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/extensions/api/generated_schemas.h"
#include "extensions/common/alias.h"
#include "extensions/common/features/feature_provider.h"
#include "extensions/common/features/json_feature_provider_source.h"
#include "extensions/common/features/simple_feature.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handler.h"
#include "extensions/common/manifest_handlers/permissions_parser.h"
#include "extensions/common/manifest_url_handlers.h"
#include "extensions/common/permissions/permissions_info.h"
#include "shell/common/extensions/api/api_features.h"
#include "shell/common/extensions/api/manifest_features.h"
namespace extensions {
@ -73,19 +77,14 @@ namespace electron {
AtomExtensionsAPIProvider::AtomExtensionsAPIProvider() = default;
AtomExtensionsAPIProvider::~AtomExtensionsAPIProvider() = default;
// TODO(samuelmaddock): generate API features?
void AtomExtensionsAPIProvider::AddAPIFeatures(
extensions::FeatureProvider* provider) {
// AddShellAPIFeatures(provider);
extensions::AddElectronAPIFeatures(provider);
}
void AtomExtensionsAPIProvider::AddManifestFeatures(
extensions::FeatureProvider* provider) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// TODO(samuelmaddock): why is the extensions namespace generated?
extensions::AddAtomManifestFeatures(provider);
#endif
extensions::AddElectronManifestFeatures(provider);
}
void AtomExtensionsAPIProvider::AddPermissionFeatures(
@ -104,14 +103,12 @@ void AtomExtensionsAPIProvider::AddAPIJSONSources(
}
bool AtomExtensionsAPIProvider::IsAPISchemaGenerated(const std::string& name) {
// return shell::api::ShellGeneratedSchemas::IsGenerated(name);
return false;
return extensions::api::ElectronGeneratedSchemas::IsGenerated(name);
}
base::StringPiece AtomExtensionsAPIProvider::GetAPISchema(
const std::string& name) {
// return shell::api::ShellGeneratedSchemas::Get(name);
return "";
return extensions::api::ElectronGeneratedSchemas::Get(name);
}
void AtomExtensionsAPIProvider::RegisterPermissions(

Просмотреть файл

@ -6,13 +6,13 @@
#include "content/public/renderer/render_thread.h"
#include "extensions/renderer/dispatcher.h"
#include "extensions/renderer/dispatcher_delegate.h"
#include "shell/renderer/extensions/electron_extensions_dispatcher_delegate.h"
namespace electron {
AtomExtensionsRendererClient::AtomExtensionsRendererClient()
: dispatcher_(std::make_unique<extensions::Dispatcher>(
std::make_unique<extensions::DispatcherDelegate>())) {
std::make_unique<ElectronExtensionsDispatcherDelegate>())) {
dispatcher_->OnRenderThreadStarted(content::RenderThread::Get());
}

Просмотреть файл

@ -0,0 +1,51 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "shell/renderer/extensions/electron_extensions_dispatcher_delegate.h"
#include <memory>
#include <set>
#include <string>
#include "chrome/renderer/extensions/tabs_hooks_delegate.h"
#include "extensions/renderer/bindings/api_bindings_system.h"
#include "extensions/renderer/lazy_background_page_native_handler.h"
#include "extensions/renderer/module_system.h"
#include "extensions/renderer/native_extension_bindings_system.h"
#include "extensions/renderer/native_handler.h"
using extensions::NativeHandler;
ElectronExtensionsDispatcherDelegate::ElectronExtensionsDispatcherDelegate() {}
ElectronExtensionsDispatcherDelegate::~ElectronExtensionsDispatcherDelegate() {}
void ElectronExtensionsDispatcherDelegate::RegisterNativeHandlers(
extensions::Dispatcher* dispatcher,
extensions::ModuleSystem* module_system,
extensions::NativeExtensionBindingsSystem* bindings_system,
extensions::ScriptContext* context) {
module_system->RegisterNativeHandler(
"lazy_background_page",
std::unique_ptr<NativeHandler>(
new extensions::LazyBackgroundPageNativeHandler(context)));
}
void ElectronExtensionsDispatcherDelegate::PopulateSourceMap(
extensions::ResourceBundleSourceMap* source_map) {}
void ElectronExtensionsDispatcherDelegate::RequireWebViewModules(
extensions::ScriptContext* context) {}
void ElectronExtensionsDispatcherDelegate::OnActiveExtensionsUpdated(
const std::set<std::string>& extension_ids) {}
void ElectronExtensionsDispatcherDelegate::InitializeBindingsSystem(
extensions::Dispatcher* dispatcher,
extensions::NativeExtensionBindingsSystem* bindings_system) {
extensions::APIBindingsSystem* bindings = bindings_system->api_system();
bindings->GetHooksForAPI("tabs")->SetDelegate(
std::make_unique<extensions::TabsHooksDelegate>(
bindings_system->messaging_service()));
}

Просмотреть файл

@ -0,0 +1,39 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_RENDERER_EXTENSIONS_ELECTRON_EXTENSIONS_DISPATCHER_DELEGATE_H_
#define SHELL_RENDERER_EXTENSIONS_ELECTRON_EXTENSIONS_DISPATCHER_DELEGATE_H_
#include <set>
#include <string>
#include "base/macros.h"
#include "extensions/renderer/dispatcher_delegate.h"
class ElectronExtensionsDispatcherDelegate
: public extensions::DispatcherDelegate {
public:
ElectronExtensionsDispatcherDelegate();
~ElectronExtensionsDispatcherDelegate() override;
private:
// extensions::DispatcherDelegate implementation.
void RegisterNativeHandlers(
extensions::Dispatcher* dispatcher,
extensions::ModuleSystem* module_system,
extensions::NativeExtensionBindingsSystem* bindings_system,
extensions::ScriptContext* context) override;
void PopulateSourceMap(
extensions::ResourceBundleSourceMap* source_map) override;
void RequireWebViewModules(extensions::ScriptContext* context) override;
void OnActiveExtensionsUpdated(
const std::set<std::string>& extensions_ids) override;
void InitializeBindingsSystem(
extensions::Dispatcher* dispatcher,
extensions::NativeExtensionBindingsSystem* bindings_system) override;
DISALLOW_COPY_AND_ASSIGN(ElectronExtensionsDispatcherDelegate);
};
#endif // SHELL_RENDERER_EXTENSIONS_ELECTRON_EXTENSIONS_DISPATCHER_DELEGATE_H_

Просмотреть файл

@ -121,6 +121,39 @@ ifdescribe(process.electronBinding('features').isExtensionsEnabled())('chrome ex
})
})
describe('chrome.tabs', () => {
it('executeScript', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`)
;(customSession as any).loadExtension(path.join(fixtures, 'extensions', 'chrome-api'))
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } })
await w.loadURL(url)
const message = { method: 'executeScript', args: ['1 + 2'] }
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`)
const [,, responseString] = await emittedOnce(w.webContents, 'console-message')
const response = JSON.parse(responseString)
expect(response).to.equal(3)
})
it('sendMessage receives the response', async function () {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`)
;(customSession as any).loadExtension(path.join(fixtures, 'extensions', 'chrome-api'))
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } })
await w.loadURL(url)
const message = { method: 'sendMessage', args: ['Hello World!'] }
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`)
const [,, responseString] = await emittedOnce(w.webContents, 'console-message')
const response = JSON.parse(responseString)
expect(response.message).to.equal('Hello World!')
expect(response.tabId).to.equal(w.webContents.id)
})
})
describe('background pages', () => {
it('loads a lazy background page when sending a message', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`)

Просмотреть файл

@ -17,4 +17,6 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
break
}
}
// Respond asynchronously
return true
})

Просмотреть файл

@ -12,5 +12,8 @@
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"<all_urls>"
],
"manifest_version": 2
}