X Tutup
Skip to content

Commit ceebae1

Browse files
authored
feat: partially support chrome.tabs.update (electron#30069)
1 parent cce27a0 commit ceebae1

File tree

7 files changed

+315
-7
lines changed

7 files changed

+315
-7
lines changed

docs/api/extensions.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ The following methods of `chrome.tabs` are supported:
100100

101101
- `chrome.tabs.sendMessage`
102102
- `chrome.tabs.executeScript`
103+
- `chrome.tabs.update` (partial support)
104+
- supported properties: `url`, `muted`.
103105

104106
> **Note:** In Chrome, passing `-1` as a tab ID signifies the "currently active
105107
> tab". Since Electron has no such concept, passing `-1` as a tab ID is not

shell/browser/extensions/api/tabs/tabs_api.cc

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
#include <memory>
88
#include <utility>
99

10+
#include "chrome/common/url_constants.h"
11+
#include "components/url_formatter/url_fixer.h"
12+
#include "content/public/browser/navigation_entry.h"
1013
#include "extensions/browser/extension_api_frame_id_map.h"
1114
#include "extensions/common/error_utils.h"
1215
#include "extensions/common/manifest_constants.h"
@@ -319,4 +322,182 @@ ExtensionFunction::ResponseAction TabsSetZoomSettingsFunction::Run() {
319322
return RespondNow(NoArguments());
320323
}
321324

325+
bool IsKillURL(const GURL& url) {
326+
#if DCHECK_IS_ON()
327+
// Caller should ensure that |url| is already "fixed up" by
328+
// url_formatter::FixupURL, which (among many other things) takes care
329+
// of rewriting about:kill into chrome://kill/.
330+
if (url.SchemeIs(url::kAboutScheme))
331+
DCHECK(url.IsAboutBlank() || url.IsAboutSrcdoc());
332+
#endif
333+
334+
static const char* const kill_hosts[] = {
335+
chrome::kChromeUICrashHost, chrome::kChromeUIDelayedHangUIHost,
336+
chrome::kChromeUIHangUIHost, chrome::kChromeUIKillHost,
337+
chrome::kChromeUIQuitHost, chrome::kChromeUIRestartHost,
338+
content::kChromeUIBrowserCrashHost, content::kChromeUIMemoryExhaustHost,
339+
};
340+
341+
if (!url.SchemeIs(content::kChromeUIScheme))
342+
return false;
343+
344+
return base::Contains(kill_hosts, url.host_piece());
345+
}
346+
347+
GURL ResolvePossiblyRelativeURL(const std::string& url_string,
348+
const Extension* extension) {
349+
GURL url = GURL(url_string);
350+
if (!url.is_valid() && extension)
351+
url = extension->GetResourceURL(url_string);
352+
353+
return url;
354+
}
355+
bool PrepareURLForNavigation(const std::string& url_string,
356+
const Extension* extension,
357+
GURL* return_url,
358+
std::string* error) {
359+
GURL url = ResolvePossiblyRelativeURL(url_string, extension);
360+
361+
// Ideally, the URL would only be "fixed" for user input (e.g. for URLs
362+
// entered into the Omnibox), but some extensions rely on the legacy behavior
363+
// where all navigations were subject to the "fixing". See also
364+
// https://crbug.com/1145381.
365+
url = url_formatter::FixupURL(url.spec(), "" /* = desired_tld */);
366+
367+
// Reject invalid URLs.
368+
if (!url.is_valid()) {
369+
const char kInvalidUrlError[] = "Invalid url: \"*\".";
370+
*error = ErrorUtils::FormatErrorMessage(kInvalidUrlError, url_string);
371+
return false;
372+
}
373+
374+
// Don't let the extension crash the browser or renderers.
375+
if (IsKillURL(url)) {
376+
const char kNoCrashBrowserError[] =
377+
"I'm sorry. I'm afraid I can't do that.";
378+
*error = kNoCrashBrowserError;
379+
return false;
380+
}
381+
382+
// Don't let the extension navigate directly to devtools scheme pages, unless
383+
// they have applicable permissions.
384+
if (url.SchemeIs(content::kChromeDevToolsScheme) &&
385+
!(extension->permissions_data()->HasAPIPermission(
386+
extensions::mojom::APIPermissionID::kDevtools) ||
387+
extension->permissions_data()->HasAPIPermission(
388+
extensions::mojom::APIPermissionID::kDebugger))) {
389+
const char kCannotNavigateToDevtools[] =
390+
"Cannot navigate to a devtools:// page without either the devtools or "
391+
"debugger permission.";
392+
*error = kCannotNavigateToDevtools;
393+
return false;
394+
}
395+
396+
return_url->Swap(&url);
397+
return true;
398+
}
399+
400+
TabsUpdateFunction::TabsUpdateFunction() : web_contents_(nullptr) {}
401+
402+
ExtensionFunction::ResponseAction TabsUpdateFunction::Run() {
403+
std::unique_ptr<tabs::Update::Params> params(
404+
tabs::Update::Params::Create(*args_));
405+
EXTENSION_FUNCTION_VALIDATE(params.get());
406+
407+
int tab_id = params->tab_id ? *params->tab_id : -1;
408+
auto* contents = electron::api::WebContents::FromID(tab_id);
409+
if (!contents)
410+
return RespondNow(Error("No such tab"));
411+
412+
web_contents_ = contents->web_contents();
413+
414+
// Navigate the tab to a new location if the url is different.
415+
std::string error;
416+
if (params->update_properties.url.get()) {
417+
std::string updated_url = *params->update_properties.url;
418+
if (!UpdateURL(updated_url, tab_id, &error))
419+
return RespondNow(Error(std::move(error)));
420+
}
421+
422+
if (params->update_properties.muted.get()) {
423+
contents->SetAudioMuted(*params->update_properties.muted);
424+
}
425+
426+
return RespondNow(GetResult());
427+
}
428+
429+
bool TabsUpdateFunction::UpdateURL(const std::string& url_string,
430+
int tab_id,
431+
std::string* error) {
432+
GURL url;
433+
if (!PrepareURLForNavigation(url_string, extension(), &url, error)) {
434+
return false;
435+
}
436+
437+
const bool is_javascript_scheme = url.SchemeIs(url::kJavaScriptScheme);
438+
// JavaScript URLs are forbidden in chrome.tabs.update().
439+
if (is_javascript_scheme) {
440+
const char kJavaScriptUrlsNotAllowedInTabsUpdate[] =
441+
"JavaScript URLs are not allowed in chrome.tabs.update. Use "
442+
"chrome.tabs.executeScript instead.";
443+
*error = kJavaScriptUrlsNotAllowedInTabsUpdate;
444+
return false;
445+
}
446+
447+
content::NavigationController::LoadURLParams load_params(url);
448+
449+
// Treat extension-initiated navigations as renderer-initiated so that the URL
450+
// does not show in the omnibox until it commits. This avoids URL spoofs
451+
// since URLs can be opened on behalf of untrusted content.
452+
load_params.is_renderer_initiated = true;
453+
// All renderer-initiated navigations need to have an initiator origin.
454+
load_params.initiator_origin = extension()->origin();
455+
// |source_site_instance| needs to be set so that a renderer process
456+
// compatible with |initiator_origin| is picked by Site Isolation.
457+
load_params.source_site_instance = content::SiteInstance::CreateForURL(
458+
web_contents_->GetBrowserContext(),
459+
load_params.initiator_origin->GetURL());
460+
461+
// Marking the navigation as initiated via an API means that the focus
462+
// will stay in the omnibox - see https://crbug.com/1085779.
463+
load_params.transition_type = ui::PAGE_TRANSITION_FROM_API;
464+
465+
web_contents_->GetController().LoadURLWithParams(load_params);
466+
467+
DCHECK_EQ(url,
468+
web_contents_->GetController().GetPendingEntry()->GetVirtualURL());
469+
470+
return true;
471+
}
472+
473+
ExtensionFunction::ResponseValue TabsUpdateFunction::GetResult() {
474+
if (!has_callback())
475+
return NoArguments();
476+
477+
tabs::Tab tab;
478+
479+
auto* api_web_contents = electron::api::WebContents::From(web_contents_);
480+
tab.id =
481+
std::make_unique<int>(api_web_contents ? api_web_contents->ID() : -1);
482+
// TODO(nornagon): in Chrome, the tab URL is only available to extensions
483+
// that have the "tabs" (or "activeTab") permission. We should do the same
484+
// permission check here.
485+
tab.url = std::make_unique<std::string>(
486+
web_contents_->GetLastCommittedURL().spec());
487+
488+
return ArgumentList(tabs::Get::Results::Create(std::move(tab)));
489+
}
490+
491+
void TabsUpdateFunction::OnExecuteCodeFinished(
492+
const std::string& error,
493+
const GURL& url,
494+
const base::ListValue& script_result) {
495+
if (!error.empty()) {
496+
Respond(Error(error));
497+
return;
498+
}
499+
500+
return Respond(GetResult());
501+
}
502+
322503
} // namespace extensions

shell/browser/extensions/api/tabs/tabs_api.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,25 @@ class TabsGetZoomSettingsFunction : public ExtensionFunction {
8888
DECLARE_EXTENSION_FUNCTION("tabs.getZoomSettings", TABS_GETZOOMSETTINGS)
8989
};
9090

91+
class TabsUpdateFunction : public ExtensionFunction {
92+
public:
93+
TabsUpdateFunction();
94+
95+
protected:
96+
~TabsUpdateFunction() override {}
97+
bool UpdateURL(const std::string& url, int tab_id, std::string* error);
98+
ResponseValue GetResult();
99+
100+
content::WebContents* web_contents_;
101+
102+
private:
103+
ResponseAction Run() override;
104+
void OnExecuteCodeFinished(const std::string& error,
105+
const GURL& on_url,
106+
const base::ListValue& script_result);
107+
108+
DECLARE_EXTENSION_FUNCTION("tabs.update", TABS_UPDATE)
109+
};
91110
} // namespace extensions
92111

93112
#endif // SHELL_BROWSER_EXTENSIONS_API_TABS_TABS_API_H_

shell/common/extensions/api/tabs.json

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,80 @@
352352
]
353353
}
354354
]
355+
},
356+
{
357+
"name": "update",
358+
"type": "function",
359+
"description": "Modifies the properties of a tab. Properties that are not specified in <var>updateProperties</var> are not modified.",
360+
"parameters": [
361+
{
362+
"type": "integer",
363+
"name": "tabId",
364+
"minimum": 0,
365+
"optional": true,
366+
"description": "Defaults to the selected tab of the <a href='windows#current-window'>current window</a>."
367+
},
368+
{
369+
"type": "object",
370+
"name": "updateProperties",
371+
"properties": {
372+
"url": {
373+
"type": "string",
374+
"optional": true,
375+
"description": "A URL to navigate the tab to. JavaScript URLs are not supported; use $(ref:scripting.executeScript) instead."
376+
},
377+
"active": {
378+
"type": "boolean",
379+
"optional": true,
380+
"description": "Whether the tab should be active. Does not affect whether the window is focused (see $(ref:windows.update))."
381+
},
382+
"highlighted": {
383+
"type": "boolean",
384+
"optional": true,
385+
"description": "Adds or removes the tab from the current selection."
386+
},
387+
"selected": {
388+
"deprecated": "Please use <em>highlighted</em>.",
389+
"type": "boolean",
390+
"optional": true,
391+
"description": "Whether the tab should be selected."
392+
},
393+
"pinned": {
394+
"type": "boolean",
395+
"optional": true,
396+
"description": "Whether the tab should be pinned."
397+
},
398+
"muted": {
399+
"type": "boolean",
400+
"optional": true,
401+
"description": "Whether the tab should be muted."
402+
},
403+
"openerTabId": {
404+
"type": "integer",
405+
"minimum": 0,
406+
"optional": true,
407+
"description": "The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as this tab."
408+
},
409+
"autoDiscardable": {
410+
"type": "boolean",
411+
"optional": true,
412+
"description": "Whether the tab should be discarded automatically by the browser when resources are low."
413+
}
414+
}
415+
}
416+
],
417+
"returns_async": {
418+
"name": "callback",
419+
"optional": true,
420+
"parameters": [
421+
{
422+
"name": "tab",
423+
"$ref": "Tab",
424+
"optional": true,
425+
"description": "Details about the updated tab. The $(ref:tabs.Tab) object does not contain <code>url</code>, <code>pendingUrl</code>, <code>title</code>, and <code>favIconUrl</code> if the <code>\"tabs\"</code> permission has not been requested."
426+
}
427+
]
428+
}
355429
}
356430
],
357431
"events": [

spec-main/extensions-spec.ts

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -337,9 +337,13 @@ describe('chrome extensions', () => {
337337
});
338338

339339
describe('chrome.tabs', () => {
340-
it('executeScript', async () => {
341-
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
340+
let customSession: Session;
341+
before(async () => {
342+
customSession = session.fromPartition(`persist:${uuid.v4()}`);
342343
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
344+
});
345+
346+
it('executeScript', async () => {
343347
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
344348
await w.loadURL(url);
345349

@@ -353,8 +357,6 @@ describe('chrome extensions', () => {
353357
});
354358

355359
it('connect', async () => {
356-
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
357-
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
358360
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
359361
await w.loadURL(url);
360362

@@ -368,9 +370,7 @@ describe('chrome extensions', () => {
368370
expect(response[1]).to.equal('howdy');
369371
});
370372

371-
it('sendMessage receives the response', async function () {
372-
const customSession = session.fromPartition(`persist:${uuid.v4()}`);
373-
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
373+
it('sendMessage receives the response', async () => {
374374
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
375375
await w.loadURL(url);
376376

@@ -383,6 +383,28 @@ describe('chrome extensions', () => {
383383
expect(response.message).to.equal('Hello World!');
384384
expect(response.tabId).to.equal(w.webContents.id);
385385
});
386+
387+
it('update', async () => {
388+
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
389+
await w.loadURL(url);
390+
391+
const w2 = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
392+
await w2.loadURL('about:blank');
393+
394+
const w2Navigated = emittedOnce(w2.webContents, 'did-navigate');
395+
396+
const message = { method: 'update', args: [w2.webContents.id, { url }] };
397+
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
398+
399+
const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
400+
const response = JSON.parse(responseString);
401+
402+
await w2Navigated;
403+
404+
expect(new URL(w2.getURL()).toString()).to.equal(new URL(url).toString());
405+
406+
expect(response.id).to.equal(w2.webContents.id);
407+
});
386408
});
387409

388410
describe('background pages', () => {

spec-main/fixtures/extensions/chrome-api/background.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
2323
port.postMessage('howdy');
2424
break;
2525
}
26+
27+
case 'update': {
28+
const [tabId, props] = args;
29+
chrome.tabs.update(tabId, props, sendResponse);
30+
}
2631
}
2732
// Respond asynchronously
2833
return true;

spec-main/fixtures/extensions/chrome-api/main.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ const testMap = {
3737
});
3838
});
3939
chrome.runtime.sendMessage({ method: 'connectTab', args: [name] });
40+
},
41+
update (tabId, props) {
42+
chrome.runtime.sendMessage({ method: 'update', args: [tabId, props] }, response => {
43+
console.log(JSON.stringify(response));
44+
});
4045
}
4146
};
4247

0 commit comments

Comments
 (0)
X Tutup