mirror of
https://github.com/electron/electron.git
synced 2026-02-19 03:14:51 -05:00
Compare commits
408 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d93629321e | ||
|
|
b505de0765 | ||
|
|
4c4d29eb73 | ||
|
|
993ecb5bdd | ||
|
|
d0ba8d1f69 | ||
|
|
d03fd85a90 | ||
|
|
2387d10956 | ||
|
|
558350e4bf | ||
|
|
4d960873a4 | ||
|
|
dfcb2afffd | ||
|
|
221fd9d6ce | ||
|
|
ecad7c2441 | ||
|
|
a9acc050ee | ||
|
|
29311b7d1d | ||
|
|
949ec0c7c9 | ||
|
|
91b1c0162e | ||
|
|
e20eab42d3 | ||
|
|
fe44e01dbb | ||
|
|
bc987209f8 | ||
|
|
7c2889d93a | ||
|
|
fa46c67bd3 | ||
|
|
82679f4335 | ||
|
|
75f366f4d0 | ||
|
|
1d531f29ee | ||
|
|
f75b755f21 | ||
|
|
a2929226d2 | ||
|
|
6655694cc7 | ||
|
|
1ac4d27e22 | ||
|
|
681d02a77d | ||
|
|
14eefd58c1 | ||
|
|
2beec61a50 | ||
|
|
e1ae36210b | ||
|
|
e74eac61ae | ||
|
|
f8a5c3d8ee | ||
|
|
efd18b09ca | ||
|
|
cd062ac26e | ||
|
|
a3e47196f7 | ||
|
|
1930d972fc | ||
|
|
0c4ac78dea | ||
|
|
5771f3826a | ||
|
|
a55bc6a870 | ||
|
|
dcb311d5c9 | ||
|
|
e5935eaff9 | ||
|
|
d927f1dc02 | ||
|
|
ca1cae64d9 | ||
|
|
69df216a9c | ||
|
|
2917eb1589 | ||
|
|
ec282ff385 | ||
|
|
5d98e5e78a | ||
|
|
251e7bb227 | ||
|
|
d4881625b8 | ||
|
|
348f991563 | ||
|
|
6308fc4c4e | ||
|
|
7fb719f261 | ||
|
|
d7d9d58c8b | ||
|
|
acc861dbaf | ||
|
|
18de6be607 | ||
|
|
1ae50bbeff | ||
|
|
7d129ac5c9 | ||
|
|
2cca38c036 | ||
|
|
f616c85061 | ||
|
|
393045a7e5 | ||
|
|
4a7dd267ec | ||
|
|
f2275ec32e | ||
|
|
e70c39ed60 | ||
|
|
db12e7f08b | ||
|
|
6a1c6f8d7f | ||
|
|
7bd6479573 | ||
|
|
c2de2eaaa0 | ||
|
|
62b3a6b724 | ||
|
|
c3d8337058 | ||
|
|
b3eff8ef13 | ||
|
|
6cef0d9118 | ||
|
|
65d03deacd | ||
|
|
39e55225a0 | ||
|
|
bb83758378 | ||
|
|
2716a25fcf | ||
|
|
2745d70d25 | ||
|
|
b6ffa799c5 | ||
|
|
c9bb6cd134 | ||
|
|
ac2515dd0d | ||
|
|
49436f298b | ||
|
|
542874d13b | ||
|
|
2a8e1a6de1 | ||
|
|
f5bffae462 | ||
|
|
9f80f4aa76 | ||
|
|
736150672c | ||
|
|
7434547d97 | ||
|
|
0436a27d4f | ||
|
|
6627bebdbd | ||
|
|
4a24a28467 | ||
|
|
390ed798f0 | ||
|
|
cdd2176bb6 | ||
|
|
e57b74858f | ||
|
|
3805e3c0fc | ||
|
|
5fb34249c6 | ||
|
|
06997edc3a | ||
|
|
e2b961d73c | ||
|
|
867ea38cd0 | ||
|
|
2e8f2a2f51 | ||
|
|
4da1162ffe | ||
|
|
9d3ebb1888 | ||
|
|
0b8971dec2 | ||
|
|
c8ab43a766 | ||
|
|
64c6737bb2 | ||
|
|
30b6330189 | ||
|
|
177bdd207c | ||
|
|
77fbad0333 | ||
|
|
971ec77b96 | ||
|
|
1b0c15f742 | ||
|
|
52cddbcd92 | ||
|
|
6d0feb8b79 | ||
|
|
2e096ac6bc | ||
|
|
3afe390805 | ||
|
|
d5097dd2e6 | ||
|
|
257b214cb5 | ||
|
|
945ecdd709 | ||
|
|
cb614d15aa | ||
|
|
5fbcee074d | ||
|
|
dc14161a98 | ||
|
|
299fa3a3c4 | ||
|
|
d09e7f851b | ||
|
|
84eea6fa79 | ||
|
|
0cd80cd424 | ||
|
|
78f037f639 | ||
|
|
fc75bf0a9e | ||
|
|
ddc44e1af4 | ||
|
|
5ab2749acc | ||
|
|
642c458c31 | ||
|
|
2195890a46 | ||
|
|
3413e89572 | ||
|
|
7bf69ce4ee | ||
|
|
49f5006ef0 | ||
|
|
fea59c5601 | ||
|
|
6feed17387 | ||
|
|
ec0fa836d2 | ||
|
|
56a34d3b10 | ||
|
|
bde3d403a8 | ||
|
|
8779a3ac0f | ||
|
|
b465ee721e | ||
|
|
50b0750df3 | ||
|
|
1a3da54563 | ||
|
|
fa3767564a | ||
|
|
85db7e7077 | ||
|
|
9b1d2d5b88 | ||
|
|
e8621de3f5 | ||
|
|
9942b2ba80 | ||
|
|
2bf125f82a | ||
|
|
69493ac51e | ||
|
|
6504c4bbc8 | ||
|
|
5c1e1ee5ec | ||
|
|
f39ac0764d | ||
|
|
252805ddb4 | ||
|
|
df27597c05 | ||
|
|
fa683ef8b7 | ||
|
|
16b09a676f | ||
|
|
301108ece4 | ||
|
|
5d36cdf485 | ||
|
|
c94ab729dd | ||
|
|
b35f904e58 | ||
|
|
b143042c7f | ||
|
|
10c238c0ea | ||
|
|
ad2f34491c | ||
|
|
d6c51bc456 | ||
|
|
f313d00083 | ||
|
|
2ef55e1e9e | ||
|
|
62402870fd | ||
|
|
7b2a4c9984 | ||
|
|
7958f3efbb | ||
|
|
3e90aff6fd | ||
|
|
192fc3ee2c | ||
|
|
e0e7b14bdc | ||
|
|
4cecc87c55 | ||
|
|
46e7511af9 | ||
|
|
72733bae8a | ||
|
|
38fce95417 | ||
|
|
54de33464d | ||
|
|
6c4c66d2cd | ||
|
|
839dcbbbdb | ||
|
|
05ae55d131 | ||
|
|
d7736e5924 | ||
|
|
30921548ed | ||
|
|
9059a50f93 | ||
|
|
78569e9b91 | ||
|
|
07b8b2ffdd | ||
|
|
2d18829b43 | ||
|
|
f0a9e56741 | ||
|
|
314e627df1 | ||
|
|
b5c79632ef | ||
|
|
0dcc660794 | ||
|
|
0753e4911c | ||
|
|
ff2a0a4bd3 | ||
|
|
5860b70189 | ||
|
|
d84b7fc4d4 | ||
|
|
1873d8ec81 | ||
|
|
0c19db01d9 | ||
|
|
2156a9064f | ||
|
|
6e169089f0 | ||
|
|
6855004aa5 | ||
|
|
93d9aaa99c | ||
|
|
e4a3f064de | ||
|
|
9265390164 | ||
|
|
8e6819ae71 | ||
|
|
f95d2bdfd1 | ||
|
|
737b08d130 | ||
|
|
b44024d660 | ||
|
|
d0d6e88e5a | ||
|
|
c647007ccc | ||
|
|
134c8b7ed3 | ||
|
|
4f203eee4a | ||
|
|
bb065beaa6 | ||
|
|
8481e5c08a | ||
|
|
7276a1fd8c | ||
|
|
7d18988317 | ||
|
|
68afcd16e4 | ||
|
|
72e336445a | ||
|
|
3e658c4782 | ||
|
|
e7d3b43db0 | ||
|
|
6683606449 | ||
|
|
7bcc2a2762 | ||
|
|
c04fa30944 | ||
|
|
51213f656b | ||
|
|
aba7834a17 | ||
|
|
3651c0411f | ||
|
|
cb798f26b8 | ||
|
|
215c2d3ec7 | ||
|
|
9df6131352 | ||
|
|
4d7188fd2e | ||
|
|
c69d0eea2e | ||
|
|
1e54d19e8a | ||
|
|
a660598e4c | ||
|
|
1ec2840da0 | ||
|
|
1d3cd106d1 | ||
|
|
5c5f041731 | ||
|
|
325df5afcf | ||
|
|
e261519469 | ||
|
|
042c04f95f | ||
|
|
7a78506a7d | ||
|
|
75b4db49df | ||
|
|
0f8ac92b09 | ||
|
|
119ce7d6da | ||
|
|
daa075d020 | ||
|
|
8d6b9155fb | ||
|
|
cec2bfb9ec | ||
|
|
ff1cc3c60b | ||
|
|
b4bba38862 | ||
|
|
278ff8566c | ||
|
|
323de2fbe7 | ||
|
|
cd673a3697 | ||
|
|
0097a370e3 | ||
|
|
692c510867 | ||
|
|
e6f15c4380 | ||
|
|
cce8dda92f | ||
|
|
034f750c46 | ||
|
|
120a8acfd0 | ||
|
|
01992fd65c | ||
|
|
af6a5e6c30 | ||
|
|
caac2e8fc7 | ||
|
|
9a4a049498 | ||
|
|
68059d69a5 | ||
|
|
0f7334a77e | ||
|
|
eee8bee71b | ||
|
|
2795185d46 | ||
|
|
877f096d6b | ||
|
|
b33bb3a860 | ||
|
|
86f4126051 | ||
|
|
f895162234 | ||
|
|
05e41f89b4 | ||
|
|
d7378f953a | ||
|
|
ed0b654fee | ||
|
|
c1c8cbf995 | ||
|
|
ab3aa3581a | ||
|
|
20a43d9a72 | ||
|
|
27d04084c2 | ||
|
|
46649965c9 | ||
|
|
bea84969d6 | ||
|
|
ae67ec24f3 | ||
|
|
d379693967 | ||
|
|
2fe16c60ea | ||
|
|
0853536e04 | ||
|
|
4e48867af8 | ||
|
|
6bb1d1c5b0 | ||
|
|
696cc7c414 | ||
|
|
c0c8116a29 | ||
|
|
a98ed69874 | ||
|
|
3c230ad272 | ||
|
|
f93a9607b5 | ||
|
|
e7a944e356 | ||
|
|
9131a3216a | ||
|
|
288985f032 | ||
|
|
9c1c8787e9 | ||
|
|
c55cfa7a9c | ||
|
|
f72597be06 | ||
|
|
5c12606b13 | ||
|
|
f9bf319e66 | ||
|
|
b5c3ac3e7b | ||
|
|
824028a367 | ||
|
|
2b23b145d9 | ||
|
|
128106520a | ||
|
|
7e4a9ebc27 | ||
|
|
87d3530d1b | ||
|
|
bf9dfa8247 | ||
|
|
300e902066 | ||
|
|
fa0f9e83f5 | ||
|
|
d32aa032cd | ||
|
|
3fe41bb852 | ||
|
|
58b80c2c06 | ||
|
|
2ec3da29d3 | ||
|
|
499c1a5067 | ||
|
|
544ea7a0c8 | ||
|
|
eca4a5cf4c | ||
|
|
56fc2bce30 | ||
|
|
4eea01e9b0 | ||
|
|
232392ffa0 | ||
|
|
7816fd240f | ||
|
|
bcf2d0969c | ||
|
|
ed7f5f3a0b | ||
|
|
1937aff793 | ||
|
|
cf493b995c | ||
|
|
5bbc64b416 | ||
|
|
287c9eb8c0 | ||
|
|
f4d77d97e3 | ||
|
|
593af18528 | ||
|
|
df47f85646 | ||
|
|
bd3b70a6b5 | ||
|
|
9578943848 | ||
|
|
91de226a62 | ||
|
|
7044cb69a8 | ||
|
|
66a2218723 | ||
|
|
1f95fdd5ca | ||
|
|
b4e70c72a6 | ||
|
|
61bd57f851 | ||
|
|
5ab8cb7482 | ||
|
|
d1bb54d175 | ||
|
|
c104b510b0 | ||
|
|
02a2d33edc | ||
|
|
ad8f93517e | ||
|
|
a58b5ec3f0 | ||
|
|
32e321cec1 | ||
|
|
aae1bfde05 | ||
|
|
5be9028c51 | ||
|
|
fa5bc2206c | ||
|
|
e3cbd70191 | ||
|
|
7ce5af334e | ||
|
|
5605358f99 | ||
|
|
6f44fa6dbd | ||
|
|
6e66699822 | ||
|
|
71fda62839 | ||
|
|
2b354894b2 | ||
|
|
114643a624 | ||
|
|
d32f37f549 | ||
|
|
0cba5d7a71 | ||
|
|
d76937f2b9 | ||
|
|
2cf6909f48 | ||
|
|
fb1a41926a | ||
|
|
c87ecabf19 | ||
|
|
798ef785b4 | ||
|
|
89e2fe2079 | ||
|
|
250438c2d9 | ||
|
|
1176449cc9 | ||
|
|
a06af22b99 | ||
|
|
bda746f2e6 | ||
|
|
1f7f60d505 | ||
|
|
50cc80c44e | ||
|
|
00367f0b13 | ||
|
|
5d1ada085d | ||
|
|
5b414b6f93 | ||
|
|
831bbc4b55 | ||
|
|
b89b463a63 | ||
|
|
32d3e82d88 | ||
|
|
38de02c50a | ||
|
|
b8ef450cf6 | ||
|
|
168bcaf8f3 | ||
|
|
19d26c4a0c | ||
|
|
20bf768517 | ||
|
|
71f631641e | ||
|
|
5b3c90e6c6 | ||
|
|
fb298ca3db | ||
|
|
5f07df4a3d | ||
|
|
3ecccf2ad3 | ||
|
|
4cafba5e46 | ||
|
|
3b049c9074 | ||
|
|
0c1ee8ae8b | ||
|
|
4cb842d5e3 | ||
|
|
0ab21dfc98 | ||
|
|
e3ef14e784 | ||
|
|
010c6fd5be | ||
|
|
a12d66d25e | ||
|
|
faa5d18389 | ||
|
|
042e81aecb | ||
|
|
a1b46ef8a2 | ||
|
|
7f4ab06f11 | ||
|
|
c11d6813e4 | ||
|
|
c10274663c | ||
|
|
839137c3f4 | ||
|
|
529e7e7797 | ||
|
|
2ce64944ab | ||
|
|
e6e1372ea7 | ||
|
|
9e723746e9 | ||
|
|
9a2ea12d71 | ||
|
|
877013efe4 | ||
|
|
4c9317aea0 | ||
|
|
cc9b4dd968 | ||
|
|
747842c930 | ||
|
|
174e939b26 | ||
|
|
f8df8ea9d5 | ||
|
|
da5e0e5ac2 | ||
|
|
b136c51747 |
File diff suppressed because it is too large
Load Diff
2865
.circleci/config.yml
2865
.circleci/config.yml
File diff suppressed because it is too large
Load Diff
9
.github/CODEOWNERS
vendored
9
.github/CODEOWNERS
vendored
@@ -12,7 +12,10 @@ DEPS @electron/wg-upgrades
|
||||
/script/release @electron/wg-releases
|
||||
|
||||
# Security WG
|
||||
/lib/browser/devtools.ts @electron/wg-security
|
||||
/lib/browser/guest-view-manager.ts @electron/wg-security
|
||||
/lib/browser/guest-window-proxy.ts @electron/wg-security
|
||||
/lib/browser/rpc-server.ts @electron/wg-security
|
||||
|
||||
# Remote Change Disliker
|
||||
/lib/browser/remote/ @nornagon
|
||||
/lib/renderer/remote/ @nornagon
|
||||
/lib/renderer/api/remote.ts @nornagon
|
||||
/docs/api/remote.md @nornagon
|
||||
|
||||
58
.github/ISSUE_TEMPLATE/Bug_report.md
vendored
Normal file
58
.github/ISSUE_TEMPLATE/Bug_report.md
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve Electron
|
||||
|
||||
---
|
||||
|
||||
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can.
|
||||
-->
|
||||
|
||||
### Preflight Checklist
|
||||
<!-- Please ensure you've completed the following steps by replacing [ ] with [x]-->
|
||||
|
||||
* [ ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
|
||||
* [ ] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
|
||||
* [ ] I have searched the issue tracker for an issue that matches the one I want to file, without success.
|
||||
|
||||
### Issue Details
|
||||
|
||||
* **Electron Version:**
|
||||
* <!-- (output of `node_modules/.bin/electron --version`) e.g. 4.0.3 -->
|
||||
* **Operating System:**
|
||||
* <!-- (Platform and Version) e.g. macOS 10.13.6 / Windows 10 (1803) / Ubuntu 18.04 x64 -->
|
||||
* **Last Known Working Electron version:**
|
||||
* <!-- (if applicable) e.g. 3.1.0 -->
|
||||
|
||||
### Expected Behavior
|
||||
<!-- A clear and concise description of what you expected to happen. -->
|
||||
|
||||
### Actual Behavior
|
||||
<!-- A clear and concise description of what actually happened. -->
|
||||
|
||||
### To Reproduce
|
||||
<!--
|
||||
Your best chance of getting this bug looked at quickly is to provide an example.
|
||||
-->
|
||||
|
||||
<!--
|
||||
For bugs that can be encapsulated in a small experiment, you can use Electron Fiddle (https://github.com/electron/fiddle) to publish your example to a GitHub Gist and link it your bug report.
|
||||
-->
|
||||
|
||||
<!--
|
||||
If Fiddle is insufficient to produce an example, please provide an example REPOSITORY that can be cloned and run. You can fork electron-quick-start (https://github.com/electron/electron-quick-start) and include a link to the branch with your changes.
|
||||
-->
|
||||
|
||||
<!--
|
||||
If you provide a URL, please list the commands required to clone/setup/run your repo e.g.
|
||||
```sh
|
||||
$ git clone $YOUR_URL -b $BRANCH
|
||||
$ npm install
|
||||
$ npm start || electron .
|
||||
```
|
||||
-->
|
||||
|
||||
### Screenshots
|
||||
<!-- If applicable, add screenshots to help explain your problem. -->
|
||||
|
||||
### Additional Information
|
||||
<!-- Add any other context about the problem here. -->
|
||||
77
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
77
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -1,77 +0,0 @@
|
||||
name: Bug Report
|
||||
description: Report an Electron bug
|
||||
title: "[Bug]: "
|
||||
labels: "bug :beetle:"
|
||||
body:
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Preflight Checklist
|
||||
description: Please ensure you've completed all of the following.
|
||||
options:
|
||||
- label: I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
|
||||
required: true
|
||||
- label: I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
|
||||
required: true
|
||||
- label: I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: Electron Version
|
||||
description: What version of Electron are you using?
|
||||
placeholder: 12.0.0
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: What operating system are you using?
|
||||
options:
|
||||
- Windows
|
||||
- macOS
|
||||
- Ubuntu
|
||||
- Other Linux
|
||||
- Other (specify below)
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: Operating System Version
|
||||
description: What operating system version are you using? On Windows, click Start button > Settings > System > About. On macOS, click the Apple Menu > About This Mac. On Linux, use lsb_release or uname -a.
|
||||
placeholder: "e.g. Windows 10 version 1909, macOS Catalina 10.15.7, or Ubuntu 20.04"
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: What arch are you using?
|
||||
options:
|
||||
- x64
|
||||
- ia32
|
||||
- arm64 (including Apple Silicon)
|
||||
- Other (specify below)
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: Last Known Working Electron version
|
||||
description: What is the last version of Electron this worked in, if applicable?
|
||||
placeholder: 11.0.0
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Expected Behavior
|
||||
description: A clear and concise description of what you expected to happen.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Actual Behavior
|
||||
description: A clear description of what actually happens.
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: Testcase Gist URL
|
||||
description: If you can reproduce the issue in a standalone test case, please use [Electron Fiddle](https://github.com/electron/fiddle) to create one and to publish it as a [GitHub gist](https://gist.github.com) and put the gist URL here. This is **the best way** to ensure this issue is triaged quickly.
|
||||
placeholder: https://gist.github.com/...
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional Information
|
||||
description: If your problem needs further explanation, or if the issue you're seeing cannot be reproduced in a gist, please add more information here.
|
||||
21
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
21
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@@ -1,19 +1,18 @@
|
||||
name: Feature Request
|
||||
description: Suggest an idea for Electron
|
||||
about: Suggest an idea for Electron
|
||||
title: "[Feature Request]: "
|
||||
labels: "enhancement :sparkles:"
|
||||
labels: "enhancement ✨"
|
||||
body:
|
||||
- type: checkboxes
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Preflight Checklist
|
||||
description: Please ensure you've completed all of the following.
|
||||
options:
|
||||
- label: I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
|
||||
required: true
|
||||
- label: I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
|
||||
required: true
|
||||
- label: I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
|
||||
required: true
|
||||
description: Please ensure you've completed the following steps by replacing [ ] with [x]
|
||||
value: |
|
||||
* [ ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
|
||||
* [ ] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
|
||||
* [ ] I have searched the issue tracker for a feature request that matches the one I want to file, without success.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Problem Description
|
||||
|
||||
25
.github/ISSUE_TEMPLATE/mac_app_store_private_api_rejection.md
vendored
Normal file
25
.github/ISSUE_TEMPLATE/mac_app_store_private_api_rejection.md
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: Mac App Store Private API Rejection
|
||||
about: Your app was rejected from the Mac App Store for using private API's
|
||||
|
||||
---
|
||||
|
||||
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can.
|
||||
-->
|
||||
|
||||
### Preflight Checklist
|
||||
<!-- Please ensure you've completed the following steps by replacing [ ] with [x]-->
|
||||
|
||||
* [ ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
|
||||
* [ ] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
|
||||
|
||||
### Issue Details
|
||||
|
||||
* **Electron Version:**
|
||||
* <!-- (output of `node_modules/.bin/electron --version`) e.g. 4.0.3 -->
|
||||
|
||||
### Rejection Email
|
||||
<!-- Paste the contents of your rejection email here, censoring any private information such as app names.-->
|
||||
|
||||
### Additional Information
|
||||
<!-- Add any other context about the problem here. -->
|
||||
@@ -1,30 +0,0 @@
|
||||
name: Report Mac App Store Private API Rejection
|
||||
description: Your app was rejected from the Mac App Store for using private API's
|
||||
title: "[MAS Rejection]: "
|
||||
body:
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Preflight Checklist
|
||||
description: Please ensure you've completed all of the following.
|
||||
options:
|
||||
- label: I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
|
||||
required: true
|
||||
- label: I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: Electron Version
|
||||
description: What version of Electron are you using?
|
||||
placeholder: 12.0.0
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Rejection Email
|
||||
description: Paste the contents of your rejection email here, censoring any private information such as app names.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional Information
|
||||
description: Add any other context about the problem here.
|
||||
18
.gitignore
vendored
18
.gitignore
vendored
@@ -17,6 +17,24 @@
|
||||
*.xcodeproj
|
||||
/.idea/
|
||||
/dist/
|
||||
/external_binaries/
|
||||
/out/
|
||||
/vendor/.gclient
|
||||
/vendor/debian_jessie_mips64-sysroot/
|
||||
/vendor/debian_stretch_amd64-sysroot/
|
||||
/vendor/debian_stretch_arm-sysroot/
|
||||
/vendor/debian_stretch_arm64-sysroot/
|
||||
/vendor/debian_stretch_i386-sysroot/
|
||||
/vendor/gcc-4.8.3-d197-n64-loongson/
|
||||
/vendor/readme-gcc483-loongson.txt
|
||||
/vendor/download/
|
||||
/vendor/llvm-build/
|
||||
/vendor/llvm/
|
||||
/vendor/npm/
|
||||
/vendor/python_26/
|
||||
/vendor/native_mksnapshot
|
||||
/vendor/LICENSES.chromium.html
|
||||
/vendor/pyyaml
|
||||
node_modules/
|
||||
SHASUMS256.txt
|
||||
**/package-lock.json
|
||||
|
||||
1
.husky/.gitignore
vendored
1
.husky/.gitignore
vendored
@@ -1 +0,0 @@
|
||||
_
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
npm run precommit
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
npm run prepack
|
||||
33
BUILD.gn
33
BUILD.gn
@@ -35,10 +35,6 @@ if (is_mac) {
|
||||
import("//ui/gl/features.gni")
|
||||
import("//v8/gni/v8.gni")
|
||||
import("build/rules.gni")
|
||||
|
||||
assert(
|
||||
mac_deployment_target == "10.11.0",
|
||||
"Chromium has updated the mac_deployment_target, please update this assert, update the supported versions documentation (docs/tutorial/support.md) and flag this as a breaking change")
|
||||
}
|
||||
|
||||
if (is_linux) {
|
||||
@@ -187,12 +183,6 @@ action("electron_js2c") {
|
||||
rebase_path(sources, root_build_dir)
|
||||
}
|
||||
|
||||
action("generate_config_gypi") {
|
||||
outputs = [ "$root_gen_dir/config.gypi" ]
|
||||
script = "script/generate-config-gypi.py"
|
||||
args = rebase_path(outputs) + [ target_cpu ]
|
||||
}
|
||||
|
||||
target_gen_default_app_js = "$target_gen_dir/js/default_app"
|
||||
|
||||
typescript_build("default_app_js") {
|
||||
@@ -345,7 +335,6 @@ source_set("electron_lib") {
|
||||
"//components/os_crypt",
|
||||
"//components/pref_registry",
|
||||
"//components/prefs",
|
||||
"//components/security_state/content",
|
||||
"//components/upload_list",
|
||||
"//components/user_prefs",
|
||||
"//components/viz/host",
|
||||
@@ -358,6 +347,7 @@ source_set("electron_lib") {
|
||||
"//device/bluetooth",
|
||||
"//device/bluetooth/public/cpp",
|
||||
"//gin",
|
||||
"//media/blink:blink",
|
||||
"//media/capture/mojom:video_capture",
|
||||
"//media/mojo/mojom",
|
||||
"//net:extras",
|
||||
@@ -367,7 +357,6 @@ source_set("electron_lib") {
|
||||
"//ppapi/shared_impl",
|
||||
"//printing/buildflags",
|
||||
"//services/device/public/cpp/geolocation",
|
||||
"//services/device/public/cpp/hid",
|
||||
"//services/device/public/mojom",
|
||||
"//services/proxy_resolver:lib",
|
||||
"//services/video_capture/public/mojom:constants",
|
||||
@@ -375,7 +364,6 @@ source_set("electron_lib") {
|
||||
"//skia",
|
||||
"//third_party/blink/public:blink",
|
||||
"//third_party/blink/public:blink_devtools_inspector_resources",
|
||||
"//third_party/blink/public/platform/media",
|
||||
"//third_party/boringssl",
|
||||
"//third_party/electron_node:node_lib",
|
||||
"//third_party/inspector_protocol:crdtp",
|
||||
@@ -453,10 +441,7 @@ source_set("electron_lib") {
|
||||
}
|
||||
|
||||
if (is_linux) {
|
||||
deps += [
|
||||
"//build/config/linux/gtk:gtkprint",
|
||||
"//components/crash/content/browser",
|
||||
]
|
||||
deps += [ "//components/crash/content/browser" ]
|
||||
}
|
||||
|
||||
if (is_mac) {
|
||||
@@ -528,6 +513,10 @@ source_set("electron_lib") {
|
||||
]
|
||||
if (use_x11) {
|
||||
sources += filenames.lib_sources_linux_x11
|
||||
deps += [
|
||||
"//ui/gfx/x",
|
||||
"//ui/gtk/x",
|
||||
]
|
||||
}
|
||||
configs += [ ":gio_unix" ]
|
||||
defines += [
|
||||
@@ -631,8 +620,6 @@ source_set("electron_lib") {
|
||||
sources += [
|
||||
"shell/browser/printing/print_preview_message_handler.cc",
|
||||
"shell/browser/printing/print_preview_message_handler.h",
|
||||
"shell/browser/printing/print_view_manager_electron.cc",
|
||||
"shell/browser/printing/print_view_manager_electron.h",
|
||||
"shell/renderer/printing/print_render_frame_helper_delegate.cc",
|
||||
"shell/renderer/printing/print_render_frame_helper_delegate.h",
|
||||
]
|
||||
@@ -1182,6 +1169,11 @@ if (is_mac) {
|
||||
"//build/config/win:delayloads",
|
||||
]
|
||||
|
||||
if (target_cpu == "arm64") {
|
||||
configs -= [ "//build/config/win:cfi_linker" ]
|
||||
ldflags += [ "/guard:cf,nolongjmp" ]
|
||||
}
|
||||
|
||||
if (current_cpu == "x86") {
|
||||
# Set the initial stack size to 0.5MiB, instead of the 1.5MiB needed by
|
||||
# Chrome's main thread. This saves significant memory on threads (like
|
||||
@@ -1411,8 +1403,7 @@ dist_zip("hunspell_dictionaries_zip") {
|
||||
}
|
||||
|
||||
copy("libcxx_headers") {
|
||||
sources = libcxx_headers + libcxx_licenses +
|
||||
[ "//buildtools/third_party/libc++/__config_site" ]
|
||||
sources = libcxx_headers + libcxx_licenses
|
||||
outputs = [ "$target_gen_dir/electron_libcxx_include/{{source_root_relative_dir}}/{{source_file_part}}" ]
|
||||
}
|
||||
|
||||
|
||||
11
DEPS
11
DEPS
@@ -15,14 +15,11 @@ gclient_gn_args = [
|
||||
|
||||
vars = {
|
||||
'chromium_version':
|
||||
'93.0.4577.82',
|
||||
'91.0.4472.164',
|
||||
'node_version':
|
||||
'v14.17.0',
|
||||
'v14.16.0',
|
||||
'nan_version':
|
||||
# The following commit hash of NAN is v2.14.2 with *only* changes to the
|
||||
# test suite. This should be updated to a specific tag when one becomes
|
||||
# available.
|
||||
'65b32af46e9d7fab2e4ff657751205b3865f4920',
|
||||
'v2.14.2',
|
||||
'squirrel.mac_version':
|
||||
'0e5d146ba13101a1302d59ea6e6e0b3cace4ae38',
|
||||
|
||||
@@ -94,7 +91,7 @@ deps = {
|
||||
'url': (Var("nodejs_git")) + '/node.git@' + (Var("node_version")),
|
||||
'condition': 'checkout_node and process_deps',
|
||||
},
|
||||
'src/third_party/pyyaml': {
|
||||
'src/electron/vendor/pyyaml': {
|
||||
'url': (Var("yaml_git")) + '/pyyaml.git@' + (Var("pyyaml_version")),
|
||||
'condition': 'checkout_pyyaml and process_deps',
|
||||
},
|
||||
|
||||
@@ -1 +1 @@
|
||||
14.2.3
|
||||
13.5.0
|
||||
@@ -53,22 +53,6 @@ steps:
|
||||
env:
|
||||
APPVEYOR_TOKEN: $(APPVEYOR_TOKEN)
|
||||
|
||||
- powershell: |
|
||||
try {
|
||||
$localArtifactPath = "$pwd\src\pdb.zip"
|
||||
$serverArtifactPath = "$env:APPVEYOR_URL/buildjobs/$env:APPVEYOR_JOB_ID/artifacts/pdb.zip"
|
||||
Invoke-RestMethod -Method Get -Uri $serverArtifactPath -OutFile $localArtifactPath -Headers @{ "Authorization" = "Bearer $env:APPVEYOR_TOKEN" }
|
||||
cd src
|
||||
& "${env:ProgramFiles(x86)}\7-Zip\7z.exe" x -y pdb.zip
|
||||
} catch {
|
||||
Write-Host "There was an exception encountered while downloading pdb files:" $_.Exception.Message
|
||||
} finally {
|
||||
$global:LASTEXITCODE = 0
|
||||
}
|
||||
displayName: 'Download pdb files for detailed stacktraces'
|
||||
env:
|
||||
APPVEYOR_TOKEN: $(APPVEYOR_TOKEN)
|
||||
|
||||
- powershell: |
|
||||
New-Item src\out\Default\gen\node_headers\Release -Type directory
|
||||
Copy-Item -path src\out\Default\electron.lib -destination src\out\Default\gen\node_headers\Release\node.lib
|
||||
@@ -79,30 +63,15 @@ steps:
|
||||
set npm_config_nodedir=%cd%\out\Default\gen\node_headers
|
||||
set npm_config_arch=arm64
|
||||
cd electron
|
||||
node script/yarn test --runners=main --runTestFilesSeperately --enable-logging --disable-features=CalculateNativeWinOcclusion
|
||||
displayName: 'Run Electron Main process tests'
|
||||
env:
|
||||
ELECTRON_ENABLE_STACK_DUMPING: true
|
||||
ELECTRON_OUT_DIR: Default
|
||||
IGNORE_YARN_INSTALL_ERROR: 1
|
||||
ELECTRON_TEST_RESULTS_DIR: junit
|
||||
MOCHA_MULTI_REPORTERS: 'mocha-junit-reporter, tap'
|
||||
MOCHA_REPORTER: mocha-multi-reporters
|
||||
|
||||
- script: |
|
||||
cd src
|
||||
set npm_config_nodedir=%cd%\out\Default\gen\node_headers
|
||||
set npm_config_arch=arm64
|
||||
cd electron
|
||||
node script/yarn test --runners=remote --enable-logging --disable-features=CalculateNativeWinOcclusion
|
||||
displayName: 'Run Electron Remote based tests'
|
||||
# CalculateNativeWinOcclusion is disabled due to https://bugs.chromium.org/p/chromium/issues/detail?id=1139022
|
||||
node script/yarn test -- --enable-logging --verbose --disable-features=CalculateNativeWinOcclusion --disable-gpu
|
||||
displayName: 'Run Electron tests'
|
||||
env:
|
||||
ELECTRON_OUT_DIR: Default
|
||||
IGNORE_YARN_INSTALL_ERROR: 1
|
||||
ELECTRON_TEST_RESULTS_DIR: junit
|
||||
MOCHA_MULTI_REPORTERS: 'mocha-junit-reporter, tap'
|
||||
MOCHA_REPORTER: mocha-multi-reporters
|
||||
condition: always()
|
||||
|
||||
- task: PublishTestResults@2
|
||||
displayName: 'Publish Test Results'
|
||||
|
||||
@@ -2,7 +2,7 @@ is_electron_build = true
|
||||
root_extra_deps = [ "//electron" ]
|
||||
|
||||
# Registry of NMVs --> https://github.com/nodejs/node/blob/master/doc/abi_version_registry.json
|
||||
node_module_version = 97
|
||||
node_module_version = 89
|
||||
|
||||
v8_promise_internal_field_count = 1
|
||||
v8_typed_array_max_size_in_heap = 0
|
||||
|
||||
@@ -39,7 +39,7 @@ def main(dump_syms, binary, out_dir, stamp_file, dsym_file=None):
|
||||
args += ["-g", dsym_file]
|
||||
args += [binary]
|
||||
|
||||
symbol_data = subprocess.check_output(args).decode(sys.stdout.encoding)
|
||||
symbol_data = subprocess.check_output(args)
|
||||
symbol_path = os.path.join(out_dir, get_symbol_path(symbol_data))
|
||||
mkdir_p(os.path.dirname(symbol_path))
|
||||
|
||||
|
||||
@@ -61,6 +61,13 @@ module.exports = ({
|
||||
);
|
||||
}
|
||||
|
||||
if (defines.ENABLE_REMOTE_MODULE === 'false') {
|
||||
ignoredModules.push(
|
||||
'@electron/internal/browser/remote/server',
|
||||
'@electron/internal/renderer/api/remote'
|
||||
);
|
||||
}
|
||||
|
||||
if (defines.ENABLE_VIEWS_API === 'false') {
|
||||
ignoredModules.push(
|
||||
'@electron/internal/browser/api/views/image-view.js'
|
||||
|
||||
@@ -39,8 +39,7 @@ PATHS_TO_SKIP = [
|
||||
'./crashpad_handler',
|
||||
# Skip because these are outputs that we don't need.
|
||||
'resources/inspector',
|
||||
'gen/third_party/devtools-frontend/src',
|
||||
'gen/ui/webui'
|
||||
'gen/third_party/devtools-frontend/src'
|
||||
]
|
||||
|
||||
def skip_path(dep, dist_zip, target_cpu):
|
||||
|
||||
@@ -12,6 +12,7 @@ buildflag_header("buildflags") {
|
||||
"ENABLE_DESKTOP_CAPTURER=$enable_desktop_capturer",
|
||||
"ENABLE_RUN_AS_NODE=$enable_run_as_node",
|
||||
"ENABLE_OSR=$enable_osr",
|
||||
"ENABLE_REMOTE_MODULE=$enable_remote_module",
|
||||
"ENABLE_VIEWS_API=$enable_views_api",
|
||||
"ENABLE_PDF_VIEWER=$enable_pdf_viewer",
|
||||
"ENABLE_TTS=$enable_tts",
|
||||
|
||||
@@ -10,6 +10,8 @@ declare_args() {
|
||||
|
||||
enable_osr = true
|
||||
|
||||
enable_remote_module = true
|
||||
|
||||
enable_views_api = true
|
||||
|
||||
enable_pdf_viewer = true
|
||||
|
||||
@@ -43,6 +43,8 @@ static_library("chrome") {
|
||||
"//chrome/browser/predictors/proxy_lookup_client_impl.h",
|
||||
"//chrome/browser/predictors/resolve_host_client_impl.cc",
|
||||
"//chrome/browser/predictors/resolve_host_client_impl.h",
|
||||
"//chrome/browser/ssl/security_state_tab_helper.cc",
|
||||
"//chrome/browser/ssl/security_state_tab_helper.h",
|
||||
"//chrome/browser/ui/views/autofill/autofill_popup_view_utils.cc",
|
||||
"//chrome/browser/ui/views/autofill/autofill_popup_view_utils.h",
|
||||
"//extensions/browser/app_window/size_constraints.cc",
|
||||
@@ -81,6 +83,7 @@ static_library("chrome") {
|
||||
"//components/keyed_service/content",
|
||||
"//components/paint_preview/buildflags",
|
||||
"//components/proxy_config",
|
||||
"//components/security_state/content",
|
||||
"//content/public/browser",
|
||||
"//services/strings",
|
||||
]
|
||||
@@ -91,10 +94,6 @@ static_library("chrome") {
|
||||
"//components/optimization_guide/proto:optimization_guide_proto",
|
||||
]
|
||||
|
||||
if (enable_basic_printing && is_win) {
|
||||
deps += [ "//chrome/common:cloud_print_utility_mojom" ]
|
||||
}
|
||||
|
||||
if (is_linux) {
|
||||
sources += [ "//chrome/browser/icon_loader_auralinux.cc" ]
|
||||
if (use_x11 || use_ozone) {
|
||||
@@ -225,6 +224,8 @@ static_library("chrome") {
|
||||
"//chrome/browser/printing/print_job_worker.h",
|
||||
"//chrome/browser/printing/print_view_manager_base.cc",
|
||||
"//chrome/browser/printing/print_view_manager_base.h",
|
||||
"//chrome/browser/printing/print_view_manager_basic.cc",
|
||||
"//chrome/browser/printing/print_view_manager_basic.h",
|
||||
"//chrome/browser/printing/printer_query.cc",
|
||||
"//chrome/browser/printing/printer_query.h",
|
||||
"//chrome/browser/printing/printing_service.cc",
|
||||
|
||||
@@ -157,14 +157,15 @@ void CertificateManagerModel::GetCertDBOnIOThread(
|
||||
CreationCallback callback) {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
|
||||
auto split_callback = base::SplitOnceCallback(base::BindOnce(
|
||||
&CertificateManagerModel::DidGetCertDBOnIOThread, std::move(callback)));
|
||||
auto did_get_cert_db_callback = base::AdaptCallbackForRepeating(
|
||||
base::BindOnce(&CertificateManagerModel::DidGetCertDBOnIOThread,
|
||||
std::move(callback)));
|
||||
|
||||
net::NSSCertDatabase* cert_db = GetNSSCertDatabaseForResourceContext(
|
||||
context, std::move(split_callback.first));
|
||||
net::NSSCertDatabase* cert_db =
|
||||
GetNSSCertDatabaseForResourceContext(context, did_get_cert_db_callback);
|
||||
|
||||
// If the NSS database was already available, |cert_db| is non-null and
|
||||
// |did_get_cert_db_callback| has not been called. Call it explicitly.
|
||||
if (cert_db)
|
||||
std::move(split_callback.second).Run(cert_db);
|
||||
did_get_cert_db_callback.Run(cert_db);
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ class ProcessSingleton {
|
||||
|
||||
// Function to call when the other process is hung and needs to be killed.
|
||||
// Allows overriding for tests.
|
||||
base::RepeatingCallback<void(int)> kill_callback_;
|
||||
base::Callback<void(int)> kill_callback_;
|
||||
|
||||
// Path in file system to the socket.
|
||||
base::FilePath socket_path_;
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
#include "chrome/browser/process_singleton.h"
|
||||
|
||||
#include <windows.h>
|
||||
#include <shellapi.h>
|
||||
|
||||
#include "base/base_paths.h"
|
||||
|
||||
@@ -52,7 +52,8 @@ async function createWindow (backgroundColor?: string) {
|
||||
webPreferences: {
|
||||
preload: path.resolve(__dirname, 'preload.js'),
|
||||
contextIsolation: true,
|
||||
sandbox: true
|
||||
sandbox: true,
|
||||
enableRemoteModule: false
|
||||
},
|
||||
useContentSize: true,
|
||||
show: false
|
||||
|
||||
@@ -109,7 +109,7 @@ function loadApplicationPackage (packagePath: string) {
|
||||
|
||||
try {
|
||||
const filePath = Module._resolveFilename(packagePath, module, true);
|
||||
app.setAppPath(appPath || path.dirname(filePath));
|
||||
app._setDefaultAppPaths(appPath || path.dirname(filePath));
|
||||
} catch (e) {
|
||||
showErrorMessage(`Unable to find Electron app at ${packagePath}\n\n${e.message}`);
|
||||
return;
|
||||
|
||||
@@ -507,6 +507,64 @@ Returns:
|
||||
Emitted when `desktopCapturer.getSources()` is called in the renderer process of `webContents`.
|
||||
Calling `event.preventDefault()` will make it return empty sources.
|
||||
|
||||
### Event: 'remote-require' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `webContents` [WebContents](web-contents.md)
|
||||
* `moduleName` String
|
||||
|
||||
Emitted when `remote.require()` is called in the renderer process of `webContents`.
|
||||
Calling `event.preventDefault()` will prevent the module from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
### Event: 'remote-get-global' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `webContents` [WebContents](web-contents.md)
|
||||
* `globalName` String
|
||||
|
||||
Emitted when `remote.getGlobal()` is called in the renderer process of `webContents`.
|
||||
Calling `event.preventDefault()` will prevent the global from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
### Event: 'remote-get-builtin' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `webContents` [WebContents](web-contents.md)
|
||||
* `moduleName` String
|
||||
|
||||
Emitted when `remote.getBuiltin()` is called in the renderer process of `webContents`.
|
||||
Calling `event.preventDefault()` will prevent the module from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
### Event: 'remote-get-current-window' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `webContents` [WebContents](web-contents.md)
|
||||
|
||||
Emitted when `remote.getCurrentWindow()` is called in the renderer process of `webContents`.
|
||||
Calling `event.preventDefault()` will prevent the object from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
### Event: 'remote-get-current-web-contents' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `webContents` [WebContents](web-contents.md)
|
||||
|
||||
Emitted when `remote.getCurrentWebContents()` is called in the renderer process of `webContents`.
|
||||
Calling `event.preventDefault()` will prevent the object from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
## Methods
|
||||
|
||||
The `app` object has the following methods:
|
||||
@@ -1427,6 +1485,19 @@ This is the user agent that will be used when no user agent is set at the
|
||||
app has the same user agent. Set to a custom value as early as possible
|
||||
in your app's initialization to ensure that your overridden value is used.
|
||||
|
||||
### `app.allowRendererProcessReuse`
|
||||
|
||||
A `Boolean` which when `true` disables the overrides that Electron has in place
|
||||
to ensure renderer processes are restarted on every navigation. The current
|
||||
default value for this property is `true`.
|
||||
|
||||
The intention is for these overrides to become disabled by default and then at
|
||||
some point in the future this property will be removed. This property impacts
|
||||
which native modules you can use in the renderer process. For more information
|
||||
on the direction Electron is going with renderer process restarts and usage of
|
||||
native modules in the renderer process please check out this
|
||||
[Tracking Issue](https://github.com/electron/electron/issues/18397).
|
||||
|
||||
### `app.runningUnderRosettaTranslation` _macOS_ _Readonly_
|
||||
|
||||
A `Boolean` which when `true` indicates that the app is currently running
|
||||
|
||||
@@ -118,9 +118,6 @@ Returns `String` - The current update feed URL.
|
||||
Asks the server whether there is an update. You must call `setFeedURL` before
|
||||
using this API.
|
||||
|
||||
**Note:** If an update is available it will be downloaded automatically.
|
||||
Calling `autoUpdater.checkForUpdates()` twice will download the update two times.
|
||||
|
||||
### `autoUpdater.quitAndInstall()`
|
||||
|
||||
Restarts the app and installs the update after it has been downloaded. It
|
||||
|
||||
@@ -14,7 +14,7 @@ const win = new BrowserWindow({ width: 800, height: 600 })
|
||||
win.loadURL('https://github.com')
|
||||
|
||||
// Or load a local HTML file
|
||||
win.loadFile('index.html')
|
||||
win.loadURL(`file://${__dirname}/app/index.html`)
|
||||
```
|
||||
|
||||
## Frameless window
|
||||
@@ -22,13 +22,12 @@ win.loadFile('index.html')
|
||||
To create a window without chrome, or a transparent window in arbitrary shape,
|
||||
you can use the [Frameless Window](frameless-window.md) API.
|
||||
|
||||
## Showing the window gracefully
|
||||
## Showing window gracefully
|
||||
|
||||
When loading a page in the window directly, users may see the page load incrementally,
|
||||
which is not a good experience for a native app. To make the window display
|
||||
without a visual flash, there are two solutions for different situations.
|
||||
When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display
|
||||
without visual flash, there are two solutions for different situations.
|
||||
|
||||
### Using the `ready-to-show` event
|
||||
## Using `ready-to-show` event
|
||||
|
||||
While loading the page, the `ready-to-show` event will be emitted when the renderer
|
||||
process has rendered the page for the first time if the window has not been shown yet. Showing
|
||||
@@ -49,7 +48,7 @@ event.
|
||||
Please note that using this event implies that the renderer will be considered "visible" and
|
||||
paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false`
|
||||
|
||||
### Setting the `backgroundColor` property
|
||||
## Setting `backgroundColor`
|
||||
|
||||
For a complex app, the `ready-to-show` event could be emitted too late, making
|
||||
the app feel slow. In this case, it is recommended to show the window
|
||||
@@ -271,6 +270,8 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
|
||||
OS-level sandbox and disabling the Node.js engine. This is not the same as
|
||||
the `nodeIntegration` option and the APIs available to the preload script
|
||||
are more limited. Read more about the option [here](../tutorial/sandbox.md).
|
||||
* `enableRemoteModule` Boolean (optional) - Whether to enable the [`remote`](remote.md) module.
|
||||
Default is `false`.
|
||||
* `session` [Session](session.md#class-session) (optional) - Sets the session used by the
|
||||
page. Instead of passing the Session object directly, you can also choose to
|
||||
use the `partition` option instead, which accepts a partition string. When
|
||||
@@ -282,6 +283,13 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
|
||||
same `partition`. If there is no `persist:` prefix, the page will use an
|
||||
in-memory session. By assigning the same `partition`, multiple pages can share
|
||||
the same session. Default is the default session.
|
||||
* `affinity` String (optional) - When specified, web pages with the same
|
||||
`affinity` will run in the same renderer process. Note that due to reusing
|
||||
the renderer process, certain `webPreferences` options will also be shared
|
||||
between the web pages even when you specified different values for them,
|
||||
including but not limited to `preload`, `sandbox` and `nodeIntegration`.
|
||||
So it is suggested to use exact same `webPreferences` for web pages with
|
||||
the same `affinity`. _Deprecated_
|
||||
* `zoomFactor` Number (optional) - The default zoom factor of the page, `3.0` represents
|
||||
`300%`. Default is `1.0`.
|
||||
* `javascript` Boolean (optional) - Enables JavaScript support. Default is `true`.
|
||||
@@ -339,10 +347,12 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
|
||||
[Chrome Content Scripts][chrome-content-scripts]. You can access this
|
||||
context in the dev tools by selecting the 'Electron Isolated Context'
|
||||
entry in the combo box at the top of the Console tab.
|
||||
* `worldSafeExecuteJavaScript` Boolean (optional) - If true, values returned from `webFrame.executeJavaScript` will be sanitized to ensure JS values
|
||||
can't unsafely cross between worlds when using `contextIsolation`. Defaults to `true`. _Deprecated_
|
||||
* `nativeWindowOpen` Boolean (optional) - Whether to use native
|
||||
`window.open()`. Defaults to `false`. Child windows will always have node
|
||||
integration disabled unless `nodeIntegrationInSubFrames` is true. **Note:** The default
|
||||
value will be changing to `true` in Electron 15.
|
||||
integration disabled unless `nodeIntegrationInSubFrames` is true. **Note:** This option is currently
|
||||
experimental.
|
||||
* `webviewTag` Boolean (optional) - Whether to enable the [`<webview>` tag](webview-tag.md).
|
||||
Defaults to `false`. **Note:** The
|
||||
`preload` script configured for the `<webview>` will have node integration
|
||||
@@ -750,10 +760,6 @@ A `Boolean` property that determines whether the window is in simple (pre-Lion)
|
||||
|
||||
A `Boolean` property that determines whether the window is in fullscreen mode.
|
||||
|
||||
#### `win.focusable` _Windows_ _macOS_
|
||||
|
||||
A `Boolean` property that determines whether the window is focusable.
|
||||
|
||||
#### `win.visibleOnAllWorkspaces`
|
||||
|
||||
A `Boolean` property that determines whether the window is visible on all workspaces.
|
||||
@@ -1672,10 +1678,6 @@ Changes whether the window can be focused.
|
||||
|
||||
On macOS it does not remove the focus from the window.
|
||||
|
||||
#### `win.isFocusable()` _macOS_ _Windows_
|
||||
|
||||
Returns whether the window can be focused.
|
||||
|
||||
#### `win.setParentWindow(parent)`
|
||||
|
||||
* `parent` BrowserWindow | null
|
||||
@@ -1685,7 +1687,7 @@ current window into a top-level window.
|
||||
|
||||
#### `win.getParentWindow()`
|
||||
|
||||
Returns `BrowserWindow | null` - The parent window or `null` if there is no parent.
|
||||
Returns `BrowserWindow` - The parent window.
|
||||
|
||||
#### `win.getChildWindows()`
|
||||
|
||||
|
||||
@@ -199,7 +199,7 @@ const { clipboard } = require('electron')
|
||||
|
||||
const hasFormat = clipboard.has('<p>selection</p>')
|
||||
console.log(hasFormat)
|
||||
// 'true' or 'false'
|
||||
// 'true' or 'false
|
||||
```
|
||||
|
||||
### `clipboard.read(format)` _Experimental_
|
||||
@@ -208,10 +208,6 @@ console.log(hasFormat)
|
||||
|
||||
Returns `String` - Reads `format` type from the clipboard.
|
||||
|
||||
`format` should contain valid ASCII characters and have `/` separator.
|
||||
`a/c`, `a/bc` are valid formats while `/abc`, `abc/`, `a/`, `/a`, `a`
|
||||
are not valid.
|
||||
|
||||
### `clipboard.readBuffer(format)` _Experimental_
|
||||
|
||||
* `format` String
|
||||
@@ -222,9 +218,9 @@ Returns `Buffer` - Reads `format` type from the clipboard.
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
const buffer = Buffer.from('this is binary', 'utf8')
|
||||
clipboard.writeBuffer('public/utf8-plain-text', buffer)
|
||||
clipboard.writeBuffer('public.utf8-plain-text', buffer)
|
||||
|
||||
const ret = clipboard.readBuffer('public/utf8-plain-text')
|
||||
const ret = clipboard.readBuffer('public.utf8-plain-text')
|
||||
|
||||
console.log(buffer.equals(out))
|
||||
// true
|
||||
@@ -242,7 +238,7 @@ Writes the `buffer` into the clipboard as `format`.
|
||||
const { clipboard } = require('electron')
|
||||
|
||||
const buffer = Buffer.from('writeBuffer', 'utf8')
|
||||
clipboard.writeBuffer('public/utf8-plain-text', buffer)
|
||||
clipboard.writeBuffer('public.utf8-plain-text', buffer)
|
||||
```
|
||||
|
||||
### `clipboard.write(data[, type])`
|
||||
|
||||
@@ -66,23 +66,19 @@ Forces the maximum disk space to be used by the disk cache, in bytes.
|
||||
Enables caller stack logging for the following APIs (filtering events):
|
||||
|
||||
* `desktopCapturer.getSources()` / `desktop-capturer-get-sources`
|
||||
* `remote.require()` / `remote-require`
|
||||
* `remote.getGlobal()` / `remote-get-builtin`
|
||||
* `remote.getBuiltin()` / `remote-get-global`
|
||||
* `remote.getCurrentWindow()` / `remote-get-current-window`
|
||||
* `remote.getCurrentWebContents()` / `remote-get-current-web-contents`
|
||||
|
||||
### --enable-logging[=file]
|
||||
### --enable-logging
|
||||
|
||||
Prints Chromium's logging to stderr (or a log file).
|
||||
Prints Chromium's logging into console.
|
||||
|
||||
The `ELECTRON_ENABLE_LOGGING` environment variable has the same effect as
|
||||
passing `--enable-logging`.
|
||||
|
||||
Passing `--enable-logging` will result in logs being printed on stderr.
|
||||
Passing `--enable-logging=file` will result in logs being saved to the file
|
||||
specified by `--log-file=...`, or to `electron_debug.log` in the user-data
|
||||
directory if `--log-file` is not specified.
|
||||
|
||||
> **Note:** On Windows, logs from child processes cannot be sent to stderr.
|
||||
> Logging to a file is the most reliable way to collect logs on Windows.
|
||||
|
||||
See also `--log-file`, `--log-level`, `--v`, and `--vmodule`.
|
||||
This switch can not be used in `app.commandLine.appendSwitch` since it is parsed
|
||||
earlier than user's app is loaded, but you can set the `ELECTRON_ENABLE_LOGGING`
|
||||
environment variable to achieve the same effect.
|
||||
|
||||
### --force-fieldtrials=`trials`
|
||||
|
||||
@@ -135,37 +131,10 @@ See the [Node.js documentation][node-cli] or run `node --help` in your terminal
|
||||
|
||||
Set a custom locale.
|
||||
|
||||
### --log-file=`path`
|
||||
|
||||
If `--enable-logging` is specified, logs will be written to the given path. The
|
||||
parent directory must exist.
|
||||
|
||||
Setting the `ELECTRON_LOG_FILE` environment variable is equivalent to passing
|
||||
this flag. If both are present, the command-line switch takes precedence.
|
||||
|
||||
### --log-net-log=`path`
|
||||
|
||||
Enables net log events to be saved and writes them to `path`.
|
||||
|
||||
### --log-level=`N`
|
||||
|
||||
Sets the verbosity of logging when used together with `--enable-logging`.
|
||||
`N` should be one of [Chrome's LogSeverities][severities].
|
||||
|
||||
Note that two complimentary logging mechanisms in Chromium -- `LOG()`
|
||||
and `VLOG()` -- are controlled by different switches. `--log-level`
|
||||
controls `LOG()` messages, while `--v` and `--vmodule` control `VLOG()`
|
||||
messages. So you may want to use a combination of these three switches
|
||||
depending on the granularity you want and what logging calls are made
|
||||
by the code you're trying to watch.
|
||||
|
||||
See [Chromium Logging source][logging] for more information on how
|
||||
`LOG()` and `VLOG()` interact. Loosely speaking, `VLOG()` can be thought
|
||||
of as sub-levels / per-module levels inside `LOG(INFO)` to control the
|
||||
firehose of `LOG(INFO)` data.
|
||||
|
||||
See also `--enable-logging`, `--log-level`, `--v`, and `--vmodule`.
|
||||
|
||||
### --no-proxy-server
|
||||
|
||||
Don't use a proxy server and always make direct connections. Overrides any other
|
||||
@@ -217,8 +186,6 @@ positive values are used for V-logging levels.
|
||||
|
||||
This switch only works when `--enable-logging` is also passed.
|
||||
|
||||
See also `--enable-logging`, `--log-level`, and `--vmodule`.
|
||||
|
||||
### --vmodule=`pattern`
|
||||
|
||||
Gives the per-module maximal V-logging levels to override the value given by
|
||||
@@ -231,8 +198,6 @@ logging level for all code in the source files under a `foo/bar` directory.
|
||||
|
||||
This switch only works when `--enable-logging` is also passed.
|
||||
|
||||
See also `--enable-logging`, `--log-level`, and `--v`.
|
||||
|
||||
### --force_high_performance_gpu
|
||||
|
||||
Force using discrete GPU when there are multiple GPUs available.
|
||||
@@ -280,8 +245,4 @@ By default inspector websocket url is available in stderr and under /json/list e
|
||||
[ready]: app.md#event-ready
|
||||
[play-silent-audio]: https://github.com/atom/atom/pull/9485/files
|
||||
[debugging-main-process]: ../tutorial/debugging-main-process.md
|
||||
[logging]: https://source.chromium.org/chromium/chromium/src/+/master:base/logging.h
|
||||
[node-cli]: https://nodejs.org/api/cli.html
|
||||
[play-silent-audio]: https://github.com/atom/atom/pull/9485/files
|
||||
[ready]: app.md#event-ready
|
||||
[severities]: https://source.chromium.org/chromium/chromium/src/+/master:base/logging.h?q=logging::LogSeverity&ss=chromium
|
||||
|
||||
@@ -233,6 +233,10 @@ expanding and collapsing the dialog.
|
||||
be selected by default when the message box opens.
|
||||
* `title` String (optional) - Title of the message box, some platforms will not show it.
|
||||
* `detail` String (optional) - Extra information of the message.
|
||||
* `checkboxLabel` String (optional) - If provided, the message box will
|
||||
include a checkbox with the given label.
|
||||
* `checkboxChecked` Boolean (optional) - Initial checked state of the
|
||||
checkbox. `false` by default.
|
||||
* `icon` ([NativeImage](native-image.md) | String) (optional)
|
||||
* `cancelId` Integer (optional) - The index of the button to be used to cancel the dialog, via
|
||||
the `Esc` key. By default this is assigned to the first button with "cancel" or "no" as the
|
||||
|
||||
@@ -118,19 +118,7 @@ debugging purposes.
|
||||
|
||||
### `ELECTRON_ENABLE_LOGGING`
|
||||
|
||||
Prints Chromium's internal logging to the console.
|
||||
|
||||
Setting this variable is the same as passing `--enable-logging`
|
||||
on the command line. For more info, see `--enable-logging` in [command-line
|
||||
switches](./command-line-switches.md#enable-loggingfile).
|
||||
|
||||
### `ELECTRON_LOG_FILE`
|
||||
|
||||
Sets the file destination for Chromium's internal logging.
|
||||
|
||||
Setting this variable is the same as passing `--log-file`
|
||||
on the command line. For more info, see `--log-file` in [command-line
|
||||
switches](./command-line-switches.md#log-filepath).
|
||||
Prints Chrome's internal logging to the console.
|
||||
|
||||
### `ELECTRON_DEBUG_DRAG_REGIONS`
|
||||
|
||||
@@ -139,8 +127,7 @@ green and non-draggable regions will be colored red to aid debugging.
|
||||
|
||||
### `ELECTRON_DEBUG_NOTIFICATIONS`
|
||||
|
||||
Adds extra logs to [`Notification`](./notification.md) lifecycles on macOS to aid in debugging. Extra logging will be displayed when new Notifications are created or activated. They will also be displayed when common a
|
||||
tions are taken: a notification is shown, dismissed, its button is clicked, or it is replied to.
|
||||
Adds extra logs to [`Notification`](./notification.md) lifecycles on macOS to aid in debugging. Extra logging will be displayed when new Notifications are created or activated. They will also be displayed when common actions are taken: a notification is shown, dismissed, its button is clicked, or it is replied to.
|
||||
|
||||
Sample output:
|
||||
|
||||
|
||||
@@ -78,7 +78,6 @@ The following methods of `chrome.runtime` are supported:
|
||||
- `chrome.runtime.getURL`
|
||||
- `chrome.runtime.connect`
|
||||
- `chrome.runtime.sendMessage`
|
||||
- `chrome.runtime.reload`
|
||||
|
||||
The following events of `chrome.runtime` are supported:
|
||||
|
||||
|
||||
@@ -40,8 +40,6 @@ ipcMain.on('synchronous-message', (event, arg) => {
|
||||
|
||||
```javascript
|
||||
// In renderer process (web page).
|
||||
// NB. Electron APIs are only accessible from preload, unless contextIsolation is disabled.
|
||||
// See https://www.electronjs.org/docs/tutorial/process-model#preload-scripts for more details.
|
||||
const { ipcRenderer } = require('electron')
|
||||
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ See [`Menu`](menu.md) for examples.
|
||||
* `menuItem` MenuItem
|
||||
* `browserWindow` [BrowserWindow](browser-window.md) | undefined - This will not be defined if no window is open.
|
||||
* `event` [KeyboardEvent](structures/keyboard-event.md)
|
||||
* `role` String (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `toggleSpellChecker`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu` - Define the action of the menu item, when specified the
|
||||
* `role` String (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu` - Define the action of the menu item, when specified the
|
||||
`click` property will be ignored. See [roles](#roles).
|
||||
* `type` String (optional) - Can be `normal`, `separator`, `submenu`, `checkbox` or
|
||||
`radio`.
|
||||
@@ -155,7 +155,7 @@ A `String` indicating the type of the item. Can be `normal`, `separator`, `subme
|
||||
|
||||
#### `menuItem.role`
|
||||
|
||||
A `String` (optional) indicating the item's role, if set. Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `toggleSpellChecker`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu`
|
||||
A `String` (optional) indicating the item's role, if set. Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu`
|
||||
|
||||
#### `menuItem.accelerator`
|
||||
|
||||
|
||||
@@ -8,11 +8,11 @@ Process: [Main](../glossary.md#main-process)
|
||||
|
||||
The `powerMonitor` module emits the following events:
|
||||
|
||||
### Event: 'suspend'
|
||||
### Event: 'suspend' _macOS_ _Windows_
|
||||
|
||||
Emitted when the system is suspending.
|
||||
|
||||
### Event: 'resume'
|
||||
### Event: 'resume' _macOS_ _Windows_
|
||||
|
||||
Emitted when system is resuming.
|
||||
|
||||
|
||||
217
docs/api/remote.md
Normal file
217
docs/api/remote.md
Normal file
@@ -0,0 +1,217 @@
|
||||
# remote
|
||||
|
||||
> Use main process modules from the renderer process.
|
||||
|
||||
Process: [Renderer](../glossary.md#renderer-process)
|
||||
|
||||
> ⚠️ WARNING ⚠️
|
||||
> The `remote` module is [deprecated](https://github.com/electron/electron/issues/21408).
|
||||
> Instead of `remote`, use [`ipcRenderer`](ipc-renderer.md) and
|
||||
> [`ipcMain`](ipc-main.md).
|
||||
>
|
||||
> Read more about why the `remote` module is deprecated [here](https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31).
|
||||
>
|
||||
> If you still want to use `remote` despite the performance and security
|
||||
> concerns, see [@electron/remote](https://github.com/electron/remote).
|
||||
|
||||
The `remote` module provides a simple way to do inter-process communication
|
||||
(IPC) between the renderer process (web page) and the main process.
|
||||
|
||||
In Electron, GUI-related modules (such as `dialog`, `menu` etc.) are only
|
||||
available in the main process, not in the renderer process. In order to use them
|
||||
from the renderer process, the `ipc` module is necessary to send inter-process
|
||||
messages to the main process. With the `remote` module, you can invoke methods
|
||||
of the main process object without explicitly sending inter-process messages,
|
||||
similar to Java's [RMI][rmi]. An example of creating a browser window from a
|
||||
renderer process:
|
||||
|
||||
```javascript
|
||||
const { BrowserWindow } = require('electron').remote
|
||||
const win = new BrowserWindow({ width: 800, height: 600 })
|
||||
win.loadURL('https://github.com')
|
||||
```
|
||||
|
||||
**Note:** For the reverse (access the renderer process from the main process),
|
||||
you can use [webContents.executeJavaScript](web-contents.md#contentsexecutejavascriptcode-usergesture).
|
||||
|
||||
**Note:** The remote module can be disabled for security reasons in the following contexts:
|
||||
|
||||
* [`BrowserWindow`](browser-window.md) - by setting the `enableRemoteModule` option to `false`.
|
||||
* [`<webview>`](webview-tag.md) - by setting the `enableremotemodule` attribute to `false`.
|
||||
|
||||
## Remote Objects
|
||||
|
||||
Each object (including functions) returned by the `remote` module represents an
|
||||
object in the main process (we call it a remote object or remote function).
|
||||
When you invoke methods of a remote object, call a remote function, or create
|
||||
a new object with the remote constructor (function), you are actually sending
|
||||
synchronous inter-process messages.
|
||||
|
||||
In the example above, both [`BrowserWindow`](browser-window.md) and `win` were remote objects and
|
||||
`new BrowserWindow` didn't create a `BrowserWindow` object in the renderer
|
||||
process. Instead, it created a `BrowserWindow` object in the main process and
|
||||
returned the corresponding remote object in the renderer process, namely the
|
||||
`win` object.
|
||||
|
||||
**Note:** Only [enumerable properties][enumerable-properties] which are present
|
||||
when the remote object is first referenced are accessible via remote.
|
||||
|
||||
**Note:** Arrays and Buffers are copied over IPC when accessed via the `remote`
|
||||
module. Modifying them in the renderer process does not modify them in the main
|
||||
process and vice versa.
|
||||
|
||||
## Lifetime of Remote Objects
|
||||
|
||||
Electron makes sure that as long as the remote object in the renderer process
|
||||
lives (in other words, has not been garbage collected), the corresponding object
|
||||
in the main process will not be released. When the remote object has been
|
||||
garbage collected, the corresponding object in the main process will be
|
||||
dereferenced.
|
||||
|
||||
If the remote object is leaked in the renderer process (e.g. stored in a map but
|
||||
never freed), the corresponding object in the main process will also be leaked,
|
||||
so you should be very careful not to leak remote objects.
|
||||
|
||||
Primary value types like strings and numbers, however, are sent by copy.
|
||||
|
||||
## Passing callbacks to the main process
|
||||
|
||||
Code in the main process can accept callbacks from the renderer - for instance
|
||||
the `remote` module - but you should be extremely careful when using this
|
||||
feature.
|
||||
|
||||
First, in order to avoid deadlocks, the callbacks passed to the main process
|
||||
are called asynchronously. You should not expect the main process to
|
||||
get the return value of the passed callbacks.
|
||||
|
||||
For instance you can't use a function from the renderer process in an
|
||||
`Array.map` called in the main process:
|
||||
|
||||
```javascript
|
||||
// main process mapNumbers.js
|
||||
exports.withRendererCallback = (mapper) => {
|
||||
return [1, 2, 3].map(mapper)
|
||||
}
|
||||
|
||||
exports.withLocalCallback = () => {
|
||||
return [1, 2, 3].map(x => x + 1)
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// renderer process
|
||||
const mapNumbers = require('electron').remote.require('./mapNumbers')
|
||||
const withRendererCb = mapNumbers.withRendererCallback(x => x + 1)
|
||||
const withLocalCb = mapNumbers.withLocalCallback()
|
||||
|
||||
console.log(withRendererCb, withLocalCb)
|
||||
// [undefined, undefined, undefined], [2, 3, 4]
|
||||
```
|
||||
|
||||
As you can see, the renderer callback's synchronous return value was not as
|
||||
expected, and didn't match the return value of an identical callback that lives
|
||||
in the main process.
|
||||
|
||||
Second, the callbacks passed to the main process will persist until the
|
||||
main process garbage-collects them.
|
||||
|
||||
For example, the following code seems innocent at first glance. It installs a
|
||||
callback for the `close` event on a remote object:
|
||||
|
||||
```javascript
|
||||
require('electron').remote.getCurrentWindow().on('close', () => {
|
||||
// window was closed...
|
||||
})
|
||||
```
|
||||
|
||||
But remember the callback is referenced by the main process until you
|
||||
explicitly uninstall it. If you do not, each time you reload your window the
|
||||
callback will be installed again, leaking one callback for each restart.
|
||||
|
||||
To make things worse, since the context of previously installed callbacks has
|
||||
been released, exceptions will be raised in the main process when the `close`
|
||||
event is emitted.
|
||||
|
||||
To avoid this problem, ensure you clean up any references to renderer callbacks
|
||||
passed to the main process. This involves cleaning up event handlers, or
|
||||
ensuring the main process is explicitly told to dereference callbacks that came
|
||||
from a renderer process that is exiting.
|
||||
|
||||
## Accessing built-in modules in the main process
|
||||
|
||||
The built-in modules in the main process are added as getters in the `remote`
|
||||
module, so you can use them directly like the `electron` module.
|
||||
|
||||
```javascript
|
||||
const app = require('electron').remote.app
|
||||
console.log(app)
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
The `remote` module has the following methods:
|
||||
|
||||
### `remote.getCurrentWindow()`
|
||||
|
||||
Returns [`BrowserWindow`](browser-window.md) - The window to which this web page
|
||||
belongs.
|
||||
|
||||
**Note:** Do not use `removeAllListeners` on [`BrowserWindow`](browser-window.md).
|
||||
Use of this can remove all [`blur`](https://developer.mozilla.org/en-US/docs/Web/Events/blur)
|
||||
listeners, disable click events on touch bar buttons, and other unintended
|
||||
consequences.
|
||||
|
||||
### `remote.getCurrentWebContents()`
|
||||
|
||||
Returns [`WebContents`](web-contents.md) - The web contents of this web page.
|
||||
|
||||
### `remote.getGlobal(name)`
|
||||
|
||||
* `name` String
|
||||
|
||||
Returns `any` - The global variable of `name` (e.g. `global[name]`) in the main
|
||||
process.
|
||||
|
||||
## Properties
|
||||
|
||||
### `remote.require`
|
||||
|
||||
A `NodeJS.Require` function equivalent to `require(module)` in the main process.
|
||||
Modules specified by their relative path will resolve relative to the entrypoint
|
||||
of the main process.
|
||||
|
||||
e.g.
|
||||
|
||||
```sh
|
||||
project/
|
||||
├── main
|
||||
│ ├── foo.js
|
||||
│ └── index.js
|
||||
├── package.json
|
||||
└── renderer
|
||||
└── index.js
|
||||
```
|
||||
|
||||
```js
|
||||
// main process: main/index.js
|
||||
const { app } = require('electron')
|
||||
app.whenReady().then(() => { /* ... */ })
|
||||
```
|
||||
|
||||
```js
|
||||
// some relative module: main/foo.js
|
||||
module.exports = 'bar'
|
||||
```
|
||||
|
||||
```js
|
||||
// renderer process: renderer/index.js
|
||||
const foo = require('electron').remote.require('./foo') // bar
|
||||
```
|
||||
|
||||
### `remote.process` _Readonly_
|
||||
|
||||
A `NodeJS.Process` object. The `process` object in the main process. This is the same as
|
||||
`remote.getGlobal('process')` but is cached.
|
||||
|
||||
[rmi]: https://en.wikipedia.org/wiki/Java_remote_method_invocation
|
||||
[enumerable-properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
|
||||
@@ -179,97 +179,7 @@ Emitted when a hunspell dictionary file download fails. For details
|
||||
on the failure you should collect a netlog and inspect the download
|
||||
request.
|
||||
|
||||
#### Event: 'select-hid-device'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `details` Object
|
||||
* `deviceList` [HIDDevice[]](structures/hid-device.md)
|
||||
* `frame` [WebFrameMain](web-frame-main.md)
|
||||
* `callback` Function
|
||||
* `deviceId` String | null (optional)
|
||||
|
||||
Emitted when a HID device needs to be selected when a call to
|
||||
`navigator.hid.requestDevice` is made. `callback` should be called with
|
||||
`deviceId` to be selected; passing no arguments to `callback` will
|
||||
cancel the request. Additionally, permissioning on `navigator.hid` can
|
||||
be further managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler)
|
||||
and [ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler).
|
||||
|
||||
```javascript
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
|
||||
let win = null
|
||||
|
||||
app.whenReady().then(() => {
|
||||
win = new BrowserWindow()
|
||||
|
||||
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
|
||||
if (permission === 'hid') {
|
||||
// Add logic here to determine if permission should be given to allow HID selection
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
// Optionally, retrieve previously persisted devices from a persistent store
|
||||
const grantedDevices = fetchGrantedDevices()
|
||||
|
||||
win.webContents.session.setDevicePermissionHandler((details) => {
|
||||
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
|
||||
if (details.device.vendorId === 123 && details.device.productId === 345) {
|
||||
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
|
||||
return true
|
||||
}
|
||||
|
||||
// Search through the list of devices that have previously been granted permission
|
||||
return grantedDevices.some((grantedDevice) => {
|
||||
return grantedDevice.vendorId === details.device.vendorId &&
|
||||
grantedDevice.productId === details.device.productId &&
|
||||
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
|
||||
})
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
win.webContents.session.on('select-hid-device', (event, details, callback) => {
|
||||
event.preventDefault()
|
||||
const selectedDevice = details.deviceList.find((device) => {
|
||||
return device.vendorId === '9025' && device.productId === '67'
|
||||
})
|
||||
callback(selectedPort?.deviceId)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
#### Event: 'hid-device-added'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `details` Object
|
||||
* `device` [HIDDevice[]](structures/hid-device.md)
|
||||
* `frame` [WebFrameMain](web-frame-main.md)
|
||||
|
||||
Emitted when a new HID device becomes available. For example, when a new USB device is plugged in.
|
||||
|
||||
This event will only be emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired.
|
||||
|
||||
#### Event: 'hid-device-removed'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `details` Object
|
||||
* `device` [HIDDevice[]](structures/hid-device.md)
|
||||
* `frame` [WebFrameMain](web-frame-main.md)
|
||||
|
||||
Emitted when a HID device has been removed. For example, this event will fire when a USB device is unplugged.
|
||||
|
||||
This event will only be emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired.
|
||||
|
||||
#### Event: 'select-serial-port'
|
||||
#### Event: 'select-serial-port' _Experimental_
|
||||
|
||||
Returns:
|
||||
|
||||
@@ -286,45 +196,25 @@ cancel the request. Additionally, permissioning on `navigator.serial` can
|
||||
be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler)
|
||||
with the `serial` permission.
|
||||
|
||||
Because this is an experimental feature it is disabled by default. To enable this feature, you
|
||||
will need to use the `--enable-features=ElectronSerialChooser` command line switch. Additionally
|
||||
because this is an experimental Chromium feature you will need to set `enableBlinkFeatures: 'Serial'`
|
||||
on the `webPreferences` property when opening a BrowserWindow.
|
||||
|
||||
```javascript
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
|
||||
let win = null
|
||||
app.commandLine.appendSwitch('enable-features', 'ElectronSerialChooser')
|
||||
|
||||
app.whenReady().then(() => {
|
||||
win = new BrowserWindow({
|
||||
width: 800,
|
||||
height: 600
|
||||
})
|
||||
|
||||
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
|
||||
if (permission === 'serial') {
|
||||
// Add logic here to determine if permission should be given to allow serial selection
|
||||
return true
|
||||
height: 600,
|
||||
webPreferences: {
|
||||
enableBlinkFeatures: 'Serial'
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
// Optionally, retrieve previously persisted devices from a persistent store
|
||||
const grantedDevices = fetchGrantedDevices()
|
||||
|
||||
win.webContents.session.setDevicePermissionHandler((details) => {
|
||||
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') {
|
||||
if (details.device.vendorId === 123 && details.device.productId === 345) {
|
||||
// Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first)
|
||||
return true
|
||||
}
|
||||
|
||||
// Search through the list of devices that have previously been granted permission
|
||||
return grantedDevices.some((grantedDevice) => {
|
||||
return grantedDevice.vendorId === details.device.vendorId &&
|
||||
grantedDevice.productId === details.device.productId &&
|
||||
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
|
||||
})
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
|
||||
event.preventDefault()
|
||||
const selectedPort = portList.find((device) => {
|
||||
@@ -339,7 +229,7 @@ app.whenReady().then(() => {
|
||||
})
|
||||
```
|
||||
|
||||
#### Event: 'serial-port-added'
|
||||
#### Event: 'serial-port-added' _Experimental_
|
||||
|
||||
Returns:
|
||||
|
||||
@@ -349,7 +239,7 @@ Returns:
|
||||
|
||||
Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a new serial port becomes available. For example, this event will fire when a new USB device is plugged in.
|
||||
|
||||
#### Event: 'serial-port-removed'
|
||||
#### Event: 'serial-port-removed' _Experimental_
|
||||
|
||||
Returns:
|
||||
|
||||
@@ -616,7 +506,6 @@ win.webContents.session.setCertificateVerifyProc((request, callback) => {
|
||||
* `permissionGranted` Boolean - Allow or deny the permission.
|
||||
* `details` Object - Some properties are only available on certain permission types.
|
||||
* `externalURL` String (optional) - The url of the `openExternal` request.
|
||||
* `securityOrigin` String (optional) - The security origin of the `media` request.
|
||||
* `mediaTypes` String[] (optional) - The types of media access being requested, elements can be `video`
|
||||
or `audio`
|
||||
* `requestingUrl` String - The last URL the requesting frame loaded
|
||||
@@ -643,7 +532,7 @@ session.fromPartition('some-partition').setPermissionRequestHandler((webContents
|
||||
|
||||
* `handler` Function\<Boolean> | null
|
||||
* `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively.
|
||||
* `permission` String - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, or `serial`.
|
||||
* `permission` String - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, or `serial`.
|
||||
* `requestingOrigin` String - The origin URL of the permission check
|
||||
* `details` Object - Some properties are only available on certain permission types.
|
||||
* `embeddingOrigin` String (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks.
|
||||
@@ -671,78 +560,6 @@ session.fromPartition('some-partition').setPermissionCheckHandler((webContents,
|
||||
})
|
||||
```
|
||||
|
||||
#### `ses.setDevicePermissionHandler(handler)`
|
||||
|
||||
* `handler` Function\<Boolean> | null
|
||||
* `details` Object
|
||||
* `deviceType` String - The type of device that permission is being requested on, can be `hid` or `serial`.
|
||||
* `origin` String - The origin URL of the device permission check.
|
||||
* `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md)- the device that permission is being requested for.
|
||||
* `frame` [WebFrameMain](web-frame-main.md) - WebFrameMain checking the device permission.
|
||||
|
||||
Sets the handler which can be used to respond to device permission checks for the `session`.
|
||||
Returning `true` will allow the device to be permitted and `false` will reject it.
|
||||
To clear the handler, call `setDevicePermissionHandler(null)`.
|
||||
This handler can be used to provide default permissioning to devices without first calling for permission
|
||||
to devices (eg via `navigator.hid.requestDevice`). If this handler is not defined, the default device
|
||||
permissions as granted through device selection (eg via `navigator.hid.requestDevice`) will be used.
|
||||
Additionally, the default behavior of Electron is to store granted device permision through the lifetime
|
||||
of the corresponding WebContents. If longer term storage is needed, a developer can store granted device
|
||||
permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`.
|
||||
|
||||
```javascript
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
|
||||
let win = null
|
||||
|
||||
app.whenReady().then(() => {
|
||||
win = new BrowserWindow()
|
||||
|
||||
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
|
||||
if (permission === 'hid') {
|
||||
// Add logic here to determine if permission should be given to allow HID selection
|
||||
return true
|
||||
} else if (permission === 'serial') {
|
||||
// Add logic here to determine if permission should be given to allow serial port selection
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
// Optionally, retrieve previously persisted devices from a persistent store
|
||||
const grantedDevices = fetchGrantedDevices()
|
||||
|
||||
win.webContents.session.setDevicePermissionHandler((details) => {
|
||||
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
|
||||
if (details.device.vendorId === 123 && details.device.productId === 345) {
|
||||
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
|
||||
return true
|
||||
}
|
||||
|
||||
// Search through the list of devices that have previously been granted permission
|
||||
return grantedDevices.some((grantedDevice) => {
|
||||
return grantedDevice.vendorId === details.device.vendorId &&
|
||||
grantedDevice.productId === details.device.productId &&
|
||||
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
|
||||
})
|
||||
} else if (details.deviceType === 'serial') {
|
||||
if (details.device.vendorId === 123 && details.device.productId === 345) {
|
||||
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
win.webContents.session.on('select-hid-device', (event, details, callback) => {
|
||||
event.preventDefault()
|
||||
const selectedDevice = details.deviceList.find((device) => {
|
||||
return device.vendorId === '9025' && device.productId === '67'
|
||||
})
|
||||
callback(selectedPort?.deviceId)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
#### `ses.clearHostResolverCache()`
|
||||
|
||||
Returns `Promise<void>` - Resolves when the operation is complete.
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
# HIDDevice Object
|
||||
|
||||
* `deviceId` String - Unique identifier for the device.
|
||||
* `name` String - Name of the device.
|
||||
* `vendorId` Integer - The USB vendor ID.
|
||||
* `productId` Integer - The USB product ID.
|
||||
* `serialNumber` String (optional) - The USB device serial number.
|
||||
* `guid` String (optional) - Unique identifier for the HID interface. A device may have multiple HID interfaces.
|
||||
@@ -1,12 +0,0 @@
|
||||
# UserDefaultTypes Object
|
||||
|
||||
* `string` String
|
||||
* `boolean` Boolean
|
||||
* `integer` Number
|
||||
* `float` Number
|
||||
* `double` Number
|
||||
* `url` String
|
||||
* `array` Array\<unknown>
|
||||
* `dictionary` Record\<string, unknown>
|
||||
|
||||
This type is a helper alias, no object will never exist of this type.
|
||||
@@ -159,13 +159,13 @@ Same as `unsubscribeNotification`, but removes the subscriber from `NSWorkspace.
|
||||
|
||||
Add the specified defaults to your application's `NSUserDefaults`.
|
||||
|
||||
### `systemPreferences.getUserDefault<Type extends keyof UserDefaultTypes>(key, type)` _macOS_
|
||||
### `systemPreferences.getUserDefault(key, type)` _macOS_
|
||||
|
||||
* `key` String
|
||||
* `type` Type - Can be `string`, `boolean`, `integer`, `float`, `double`,
|
||||
* `type` String - Can be `string`, `boolean`, `integer`, `float`, `double`,
|
||||
`url`, `array` or `dictionary`.
|
||||
|
||||
Returns [`UserDefaultTypes[Type]`](structures/user-default-types.md) - The value of `key` in `NSUserDefaults`.
|
||||
Returns `any` - The value of `key` in `NSUserDefaults`.
|
||||
|
||||
Some popular `key` and `type`s are:
|
||||
|
||||
|
||||
@@ -167,8 +167,7 @@ Returns:
|
||||
* `options` BrowserWindowConstructorOptions - The options which will be used for creating the new
|
||||
[`BrowserWindow`](browser-window.md).
|
||||
* `additionalFeatures` String[] - The non-standard features (features not handled
|
||||
by Chromium or Electron) given to `window.open()`. Deprecated, and will now
|
||||
always be the empty array `[]`.
|
||||
by Chromium or Electron) given to `window.open()`.
|
||||
* `referrer` [Referrer](structures/referrer.md) - The referrer that will be
|
||||
passed to the new window. May or may not result in the `Referer` header being
|
||||
sent, depending on the referrer policy.
|
||||
@@ -223,11 +222,13 @@ Returns:
|
||||
* `frameName` String - Name given to the created window in the
|
||||
`window.open()` call.
|
||||
* `options` BrowserWindowConstructorOptions - The options used to create the
|
||||
BrowserWindow. They are merged in increasing precedence: parsed options
|
||||
from the `features` string from `window.open()`, security-related
|
||||
webPreferences inherited from the parent, and options given by
|
||||
BrowserWindow. They are merged in increasing precedence: options inherited
|
||||
from the parent, parsed options from the `features` string from
|
||||
`window.open()`, and options given by
|
||||
[`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler).
|
||||
Unrecognized options are not filtered out.
|
||||
* `additionalFeatures` String[] - The non-standard features (features not
|
||||
handled Chromium or Electron) _Deprecated_
|
||||
* `referrer` [Referrer](structures/referrer.md) - The referrer that will be
|
||||
passed to the new window. May or may not result in the `Referer` header
|
||||
being sent, depending on the referrer policy.
|
||||
@@ -394,8 +395,6 @@ win.webContents.on('will-prevent-unload', (event) => {
|
||||
})
|
||||
```
|
||||
|
||||
**Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event).
|
||||
|
||||
#### Event: 'crashed' _Deprecated_
|
||||
|
||||
Returns:
|
||||
@@ -731,8 +730,6 @@ first available device will be selected. `callback` should be called with
|
||||
`deviceId` to be selected, passing empty string to `callback` will
|
||||
cancel the request.
|
||||
|
||||
If no event listener is added for this event, all bluetooth requests will be cancelled.
|
||||
|
||||
```javascript
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
|
||||
@@ -862,6 +859,59 @@ Returns:
|
||||
Emitted when `desktopCapturer.getSources()` is called in the renderer process.
|
||||
Calling `event.preventDefault()` will make it return empty sources.
|
||||
|
||||
#### Event: 'remote-require' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` IpcMainEvent
|
||||
* `moduleName` String
|
||||
|
||||
Emitted when `remote.require()` is called in the renderer process.
|
||||
Calling `event.preventDefault()` will prevent the module from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
#### Event: 'remote-get-global' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` IpcMainEvent
|
||||
* `globalName` String
|
||||
|
||||
Emitted when `remote.getGlobal()` is called in the renderer process.
|
||||
Calling `event.preventDefault()` will prevent the global from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
#### Event: 'remote-get-builtin' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` IpcMainEvent
|
||||
* `moduleName` String
|
||||
|
||||
Emitted when `remote.getBuiltin()` is called in the renderer process.
|
||||
Calling `event.preventDefault()` will prevent the module from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
#### Event: 'remote-get-current-window' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` IpcMainEvent
|
||||
|
||||
Emitted when `remote.getCurrentWindow()` is called in the renderer process.
|
||||
Calling `event.preventDefault()` will prevent the object from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
#### Event: 'remote-get-current-web-contents' _Deprecated_
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` IpcMainEvent
|
||||
|
||||
Emitted when `remote.getCurrentWebContents()` is called in the renderer process.
|
||||
Calling `event.preventDefault()` will prevent the object from being returned.
|
||||
Custom value can be returned by setting `event.returnValue`.
|
||||
|
||||
#### Event: 'preferred-size-changed'
|
||||
|
||||
Returns:
|
||||
@@ -1170,11 +1220,8 @@ Ignore application menu shortcuts while this web contents is focused.
|
||||
without a recognized 'action' value will result in a console error and have
|
||||
the same effect as returning `{action: 'deny'}`.
|
||||
|
||||
Called before creating a window a new window is requested by the renderer, e.g.
|
||||
by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or
|
||||
submitting a form with `<form target="_blank">`. See
|
||||
[`window.open()`](window-open.md) for more details and how to use this in
|
||||
conjunction with `did-create-window`.
|
||||
Called before creating a window when `window.open()` is called from the
|
||||
renderer. See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `did-create-window`.
|
||||
|
||||
#### `contents.setAudioMuted(muted)`
|
||||
|
||||
@@ -1481,8 +1528,8 @@ win.loadURL('http://github.com')
|
||||
|
||||
win.webContents.on('did-finish-load', () => {
|
||||
// Use default printing options
|
||||
const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf')
|
||||
win.webContents.printToPDF({}).then(data => {
|
||||
const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf')
|
||||
fs.writeFile(pdfPath, data, (error) => {
|
||||
if (error) throw error
|
||||
console.log(`Wrote PDF successfully to ${pdfPath}`)
|
||||
@@ -1814,8 +1861,7 @@ End subscribing for frame presentation events.
|
||||
#### `contents.startDrag(item)`
|
||||
|
||||
* `item` Object
|
||||
* `file` String - The path to the file being dragged.
|
||||
* `files` String[] (optional) - The paths to the files being dragged. (`files` will override `file` field)
|
||||
* `file` String[] | String - The path(s) to the file(s) being dragged.
|
||||
* `icon` [NativeImage](native-image.md) | String - The image must be
|
||||
non-empty on macOS.
|
||||
|
||||
|
||||
@@ -182,9 +182,3 @@ This is not the same as the OS process ID; to read that use `frame.osProcessId`.
|
||||
An `Integer` representing the unique frame id in the current renderer process.
|
||||
Distinct `WebFrameMain` instances that refer to the same underlying frame will
|
||||
have the same `routingId`.
|
||||
|
||||
#### `frame.visibilityState` _Readonly_
|
||||
|
||||
A `string` representing the [visibility state](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState) of the frame.
|
||||
|
||||
See also how the [Page Visibility API](browser-window.md#page-visibility) is affected by other Electron APIs.
|
||||
|
||||
@@ -53,7 +53,7 @@ The following methods are available on instances of `WebRequest`:
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` String - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `resourceType` String
|
||||
* `referrer` String
|
||||
* `timestamp` Double
|
||||
* `uploadData` [UploadData[]](structures/upload-data.md)
|
||||
@@ -98,7 +98,7 @@ Some examples of valid `urls`:
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` String - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `resourceType` String
|
||||
* `referrer` String
|
||||
* `timestamp` Double
|
||||
* `requestHeaders` Record<string, string>
|
||||
@@ -127,7 +127,7 @@ The `callback` has to be called with a `response` object.
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` String - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `resourceType` String
|
||||
* `referrer` String
|
||||
* `timestamp` Double
|
||||
* `requestHeaders` Record<string, string>
|
||||
@@ -149,7 +149,7 @@ response are visible by the time this listener is fired.
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` String - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `resourceType` String
|
||||
* `referrer` String
|
||||
* `timestamp` Double
|
||||
* `statusLine` String
|
||||
@@ -182,7 +182,7 @@ The `callback` has to be called with a `response` object.
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` String - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `resourceType` String
|
||||
* `referrer` String
|
||||
* `timestamp` Double
|
||||
* `responseHeaders` Record<string, string[]> (optional)
|
||||
@@ -208,7 +208,7 @@ and response headers are available.
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` String - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `resourceType` String
|
||||
* `referrer` String
|
||||
* `timestamp` Double
|
||||
* `redirectURL` String
|
||||
@@ -235,7 +235,7 @@ redirect is about to occur.
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` String - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `resourceType` String
|
||||
* `referrer` String
|
||||
* `timestamp` Double
|
||||
* `responseHeaders` Record<string, string[]> (optional)
|
||||
@@ -260,7 +260,7 @@ completed.
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` String - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `resourceType` String
|
||||
* `referrer` String
|
||||
* `timestamp` Double
|
||||
* `fromCache` Boolean
|
||||
|
||||
@@ -130,6 +130,15 @@ inside the `webview`. All your preloads will load for every iframe, you can
|
||||
use `process.isMainFrame` to determine if you are in the main frame or not.
|
||||
This option is disabled by default in the guest page.
|
||||
|
||||
### `enableremotemodule`
|
||||
|
||||
```html
|
||||
<webview src="http://www.google.com/" enableremotemodule="false"></webview>
|
||||
```
|
||||
|
||||
A `Boolean`. When this attribute is `false` the guest page in `webview` will not have access
|
||||
to the [`remote`](remote.md) module. The remote module is unavailable by default.
|
||||
|
||||
### `plugins`
|
||||
|
||||
```html
|
||||
@@ -995,78 +1004,3 @@ Emitted when DevTools is focused / opened.
|
||||
|
||||
[runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70
|
||||
[chrome-webview]: https://developer.chrome.com/docs/extensions/reference/webviewTag/
|
||||
|
||||
### Event: 'context-menu'
|
||||
|
||||
Returns:
|
||||
|
||||
* `params` Object
|
||||
* `x` Integer - x coordinate.
|
||||
* `y` Integer - y coordinate.
|
||||
* `linkURL` String - URL of the link that encloses the node the context menu
|
||||
was invoked on.
|
||||
* `linkText` String - Text associated with the link. May be an empty
|
||||
string if the contents of the link are an image.
|
||||
* `pageURL` String - URL of the top level page that the context menu was
|
||||
invoked on.
|
||||
* `frameURL` String - URL of the subframe that the context menu was invoked
|
||||
on.
|
||||
* `srcURL` String - Source URL for the element that the context menu
|
||||
was invoked on. Elements with source URLs are images, audio and video.
|
||||
* `mediaType` String - Type of the node the context menu was invoked on. Can
|
||||
be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`.
|
||||
* `hasImageContents` Boolean - Whether the context menu was invoked on an image
|
||||
which has non-empty contents.
|
||||
* `isEditable` Boolean - Whether the context is editable.
|
||||
* `selectionText` String - Text of the selection that the context menu was
|
||||
invoked on.
|
||||
* `titleText` String - Title text of the selection that the context menu was
|
||||
invoked on.
|
||||
* `altText` String - Alt text of the selection that the context menu was
|
||||
invoked on.
|
||||
* `suggestedFilename` String - Suggested filename to be used when saving file through 'Save
|
||||
Link As' option of context menu.
|
||||
* `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection.
|
||||
* `selectionStartOffset` Number - Start position of the selection text.
|
||||
* `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked.
|
||||
* `misspelledWord` String - The misspelled word under the cursor, if any.
|
||||
* `dictionarySuggestions` String[] - An array of suggested words to show the
|
||||
user to replace the `misspelledWord`. Only available if there is a misspelled
|
||||
word and spellchecker is enabled.
|
||||
* `frameCharset` String - The character encoding of the frame on which the
|
||||
menu was invoked.
|
||||
* `inputFieldType` String - If the context menu was invoked on an input
|
||||
field, the type of that field. Possible values are `none`, `plainText`,
|
||||
`password`, `other`.
|
||||
* `spellcheckEnabled` Boolean - If the context is editable, whether or not spellchecking is enabled.
|
||||
* `menuSourceType` String - Input source that invoked the context menu.
|
||||
Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`.
|
||||
* `mediaFlags` Object - The flags for the media element the context menu was
|
||||
invoked on.
|
||||
* `inError` Boolean - Whether the media element has crashed.
|
||||
* `isPaused` Boolean - Whether the media element is paused.
|
||||
* `isMuted` Boolean - Whether the media element is muted.
|
||||
* `hasAudio` Boolean - Whether the media element has audio.
|
||||
* `isLooping` Boolean - Whether the media element is looping.
|
||||
* `isControlsVisible` Boolean - Whether the media element's controls are
|
||||
visible.
|
||||
* `canToggleControls` Boolean - Whether the media element's controls are
|
||||
toggleable.
|
||||
* `canPrint` Boolean - Whether the media element can be printed.
|
||||
* `canSave` Boolean - Whether or not the media element can be downloaded.
|
||||
* `canShowPictureInPicture` Boolean - Whether the media element can show picture-in-picture.
|
||||
* `isShowingPictureInPicture` Boolean - Whether the media element is currently showing picture-in-picture.
|
||||
* `canRotate` Boolean - Whether the media element can be rotated.
|
||||
* `canLoop` Boolean - Whether the media element can be looped.
|
||||
* `editFlags` Object - These flags indicate whether the renderer believes it
|
||||
is able to perform the corresponding action.
|
||||
* `canUndo` Boolean - Whether the renderer believes it can undo.
|
||||
* `canRedo` Boolean - Whether the renderer believes it can redo.
|
||||
* `canCut` Boolean - Whether the renderer believes it can cut.
|
||||
* `canCopy` Boolean - Whether the renderer believes it can copy.
|
||||
* `canPaste` Boolean - Whether the renderer believes it can paste.
|
||||
* `canDelete` Boolean - Whether the renderer believes it can delete.
|
||||
* `canSelectAll` Boolean - Whether the renderer believes it can select all.
|
||||
* `canEditRichly` Boolean - Whether the renderer believes it can edit text richly.
|
||||
|
||||
Emitted when there is a new context menu that needs to be handled.
|
||||
|
||||
@@ -23,8 +23,9 @@ BrowserWindow in the main process by using `webContents.setWindowOpenHandler()`
|
||||
for renderer-created windows.
|
||||
|
||||
BrowserWindow constructor options are set by, in increasing precedence
|
||||
order: parsed options from the `features` string from `window.open()`,
|
||||
security-related webPreferences inherited from the parent, and options given by
|
||||
order: options inherited from the parent, parsed options
|
||||
from the `features` string from `window.open()`, security-related webPreferences
|
||||
inherited from the parent, and options given by
|
||||
[`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler).
|
||||
Note that `webContents.setWindowOpenHandler` has final say and full privilege
|
||||
because it is invoked in the main process.
|
||||
@@ -63,8 +64,7 @@ window.open('https://github.com', '_blank', 'top=500,left=200,frame=false,nodeIn
|
||||
the parent window.
|
||||
* Non-standard features (that are not handled by Chromium or Electron) given in
|
||||
`features` will be passed to any registered `webContents`'s
|
||||
`did-create-window` event handler in the `options` argument.
|
||||
* `frameName` follows the specification of `windowName` located in the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters).
|
||||
`did-create-window` event handler in the `additionalFeatures` argument.
|
||||
|
||||
To customize or cancel the creation of the window, you can optionally set an
|
||||
override handler with `webContents.setWindowOpenHandler()` from the main
|
||||
@@ -90,7 +90,7 @@ mainWindow.webContents.setWindowOpenHandler(({ url }) => {
|
||||
|
||||
mainWindow.webContents.on('did-create-window', (childWindow) => {
|
||||
// For example...
|
||||
childWindow.webContents.on('will-navigate', (e) => {
|
||||
childWindow.webContents('will-navigate', (e) => {
|
||||
e.preventDefault()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,55 +12,9 @@ This document uses the following convention to categorize breaking changes:
|
||||
* **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release.
|
||||
* **Removed:** An API or feature was removed, and is no longer supported by Electron.
|
||||
|
||||
## Planned Breaking API Changes (15.0)
|
||||
|
||||
### Default Changed: `nativeWindowOpen` defaults to `true`
|
||||
|
||||
Prior to Electron 15, `window.open` was by default shimmed to use
|
||||
`BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work
|
||||
to open synchronously scriptable child windows, among other incompatibilities.
|
||||
`nativeWindowOpen: true` is no longer experimental, and is now the default.
|
||||
|
||||
See the documentation for [window.open in Electron](api/window-open.md)
|
||||
for more details.
|
||||
|
||||
## Planned Breaking API Changes (14.0)
|
||||
|
||||
### Removed: `remote` module
|
||||
|
||||
The `remote` module was deprecated in Electron 12, and will be removed in
|
||||
Electron 14. It is replaced by the
|
||||
[`@electron/remote`](https://github.com/electron/remote) module.
|
||||
|
||||
```js
|
||||
// Deprecated in Electron 12:
|
||||
const { BrowserWindow } = require('electron').remote
|
||||
```
|
||||
|
||||
```js
|
||||
// Replace with:
|
||||
const { BrowserWindow } = require('@electron/remote')
|
||||
|
||||
// In the main process:
|
||||
require('@electron/remote/main').initialize()
|
||||
```
|
||||
|
||||
### Removed: `app.allowRendererProcessReuse`
|
||||
|
||||
The `app.allowRendererProcessReuse` property will be removed as part of our plan to
|
||||
more closely align with Chromium's process model for security, performance and maintainability.
|
||||
|
||||
For more detailed information see [#18397](https://github.com/electron/electron/issues/18397).
|
||||
|
||||
### Removed: Browser Window Affinity
|
||||
|
||||
The `affinity` option when constructing a new `BrowserWindow` will be removed
|
||||
as part of our plan to more closely align with Chromium's process model for security,
|
||||
performance and maintainability.
|
||||
|
||||
For more detailed information see [#18397](https://github.com/electron/electron/issues/18397).
|
||||
|
||||
### API Changed: `window.open()`
|
||||
### API Changed: `window.(open)`
|
||||
|
||||
The optional parameter `frameName` will no longer set the title of the window. This now follows the specification described by the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters) under the corresponding parameter `windowName`.
|
||||
|
||||
@@ -68,59 +22,12 @@ If you were using this parameter to set the title of a window, you can instead u
|
||||
|
||||
### Removed: `worldSafeExecuteJavaScript`
|
||||
|
||||
In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please
|
||||
ensure your code works with this property enabled. It has been enabled by default since Electron
|
||||
In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please
|
||||
ensure your code works with this property enabled. It has been enabled by default since Electron
|
||||
12.
|
||||
|
||||
You will be affected by this change if you use either `webFrame.executeJavaScript` or `webFrame.executeJavaScriptInIsolatedWorld`. You will need to ensure that values returned by either of those methods are supported by the [Context Bridge API](api/context-bridge.md#parameter--error--return-type-support) as these methods use the same value passing semantics.
|
||||
|
||||
### Removed: BrowserWindowConstructorOptions inheriting from parent windows
|
||||
|
||||
Prior to Electron 14, windows opened with `window.open` would inherit
|
||||
BrowserWindow constructor options such as `transparent` and `resizable` from
|
||||
their parent window. Beginning with Electron 14, this behavior is removed, and
|
||||
windows will not inherit any BrowserWindow constructor options from their
|
||||
parents.
|
||||
|
||||
Instead, explicitly set options for the new window with `setWindowOpenHandler`:
|
||||
|
||||
```js
|
||||
webContents.setWindowOpenHandler((details) => {
|
||||
return {
|
||||
action: 'allow',
|
||||
overrideBrowserWindowOptions: {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Removed: `additionalFeatures`
|
||||
|
||||
The deprecated `additionalFeatures` property in the `new-window` and
|
||||
`did-create-window` events of WebContents has been removed. Since `new-window`
|
||||
uses positional arguments, the argument is still present, but will always be
|
||||
the empty array `[]`. (Though note, the `new-window` event itself is
|
||||
deprecated, and is replaced by `setWindowOpenHandler`.) Bare keys in window
|
||||
features will now present as keys with the value `true` in the options object.
|
||||
|
||||
```js
|
||||
// Removed in Electron 14
|
||||
// Triggered by window.open('...', '', 'my-key')
|
||||
webContents.on('did-create-window', (window, details) => {
|
||||
if (details.additionalFeatures.includes('my-key')) {
|
||||
// ...
|
||||
}
|
||||
})
|
||||
|
||||
// Replace with
|
||||
webContents.on('did-create-window', (window, details) => {
|
||||
if (details.options['my-key']) {
|
||||
// ...
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Planned Breaking API Changes (13.0)
|
||||
|
||||
### API Changed: `session.setPermissionCheckHandler(handler)`
|
||||
@@ -407,6 +314,14 @@ Setting `{ compress: false }` in `crashReporter.start` is deprecated. Nearly
|
||||
all crash ingestion servers support gzip compression. This option will be
|
||||
removed in a future version of Electron.
|
||||
|
||||
### Removed: Browser Window Affinity
|
||||
|
||||
The `affinity` option when constructing a new `BrowserWindow` will be removed
|
||||
as part of our plan to more closely align with Chromium's process model for security,
|
||||
performance and maintainability.
|
||||
|
||||
For more detailed information see [#18397](https://github.com/electron/electron/issues/18397).
|
||||
|
||||
### Default Changed: `enableRemoteModule` defaults to `false`
|
||||
|
||||
In Electron 9, using the remote module without explicitly enabling it via the
|
||||
|
||||
@@ -26,9 +26,7 @@ you prefer a graphical interface.
|
||||
* **.lldbinit**: Create or edit `~/.lldbinit` to allow Chromium code to be properly source-mapped.
|
||||
|
||||
```text
|
||||
# e.g: ['~/electron/src/tools/lldb']
|
||||
script sys.path[:0] = ['<...path/to/electron/src/tools/lldb>']
|
||||
script import lldbinit
|
||||
command script import ~/electron/src/tools/lldb/lldbinit.py
|
||||
```
|
||||
|
||||
## Attaching to and Debugging Electron
|
||||
|
||||
@@ -106,6 +106,7 @@ Common prefixes:
|
||||
* perf: A code change that improves performance
|
||||
* refactor: A code change that neither fixes a bug nor adds a feature
|
||||
* style: Changes that do not affect the meaning of the code (linting)
|
||||
* vendor: Bumping a dependency like libchromiumcontent or node
|
||||
|
||||
Other things to keep in mind when writing a commit message:
|
||||
|
||||
|
||||
@@ -83,6 +83,8 @@ Electron
|
||||
* **.github** - GitHub-specific config files including issues templates and CODEOWNERS.
|
||||
* **dist** - Temporary directory created by `script/create-dist.py` script
|
||||
when creating a distribution.
|
||||
* **external_binaries** - Downloaded binaries of third-party frameworks which
|
||||
do not support building with `gn`.
|
||||
* **node_modules** - Third party node modules used for building.
|
||||
* **npm** - Logic for installation of Electron via npm.
|
||||
* **out** - Temporary output directory of `ninja`.
|
||||
@@ -99,3 +101,4 @@ script/ - The set of all scripts Electron runs for a variety of purposes.
|
||||
```
|
||||
|
||||
* **typings** - TypeScript typings for Electron's internal code.
|
||||
* **vendor** - Source code for some third party dependencies.
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
|
||||
<title>Web Bluetooth API</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Web Bluetooth API</h1>
|
||||
|
||||
<button id="clickme">Test Bluetooth</button>
|
||||
|
||||
<p>Currently selected bluetooth device: <strong id="device-name""></strong></p>
|
||||
|
||||
<script src="./renderer.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,30 +0,0 @@
|
||||
const {app, BrowserWindow} = require('electron')
|
||||
const path = require('path')
|
||||
|
||||
function createWindow () {
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 800,
|
||||
height: 600
|
||||
})
|
||||
|
||||
mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
|
||||
event.preventDefault()
|
||||
if (deviceList && deviceList.length > 0) {
|
||||
callback(deviceList[0].deviceId)
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.loadFile('index.html')
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
createWindow()
|
||||
|
||||
app.on('activate', function () {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createWindow()
|
||||
})
|
||||
})
|
||||
|
||||
app.on('window-all-closed', function () {
|
||||
if (process.platform !== 'darwin') app.quit()
|
||||
})
|
||||
@@ -1,8 +0,0 @@
|
||||
async function testIt() {
|
||||
const device = await navigator.bluetooth.requestDevice({
|
||||
acceptAllDevices: true
|
||||
})
|
||||
document.getElementById('device-name').innerHTML = device.name || `ID: ${device.id}`
|
||||
}
|
||||
|
||||
document.getElementById('clickme').addEventListener('click',testIt)
|
||||
@@ -1,21 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
|
||||
<title>WebHID API</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>WebHID API</h1>
|
||||
|
||||
<button id="clickme">Test WebHID</button>
|
||||
|
||||
<h3>HID devices automatically granted access via <i>setDevicePermissionHandler</i></h3>
|
||||
<div id="granted-devices"></div>
|
||||
|
||||
<h3>HID devices automatically granted access via <i>select-hid-device</i></h3>
|
||||
<div id="granted-devices2"></div>
|
||||
|
||||
<script src="./renderer.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,50 +0,0 @@
|
||||
const {app, BrowserWindow} = require('electron')
|
||||
const path = require('path')
|
||||
|
||||
function createWindow () {
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 800,
|
||||
height: 600
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.on('select-hid-device', (event, details, callback) => {
|
||||
event.preventDefault()
|
||||
if (details.deviceList && details.deviceList.length > 0) {
|
||||
callback(details.deviceList[0].deviceId)
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.on('hid-device-added', (event, device) => {
|
||||
console.log('hid-device-added FIRED WITH', device)
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.on('hid-device-removed', (event, device) => {
|
||||
console.log('hid-device-removed FIRED WITH', device)
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
|
||||
if (permission === 'hid' && details.securityOrigin === 'file:///') {
|
||||
return true
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.setDevicePermissionHandler((details) => {
|
||||
if (details.deviceType === 'hid' && details.origin === 'file://') {
|
||||
return true
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.loadFile('index.html')
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
createWindow()
|
||||
|
||||
app.on('activate', function () {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createWindow()
|
||||
})
|
||||
})
|
||||
|
||||
app.on('window-all-closed', function () {
|
||||
if (process.platform !== 'darwin') app.quit()
|
||||
})
|
||||
@@ -1,19 +0,0 @@
|
||||
async function testIt() {
|
||||
const grantedDevices = await navigator.hid.getDevices()
|
||||
let grantedDeviceList = ''
|
||||
grantedDevices.forEach(device => {
|
||||
grantedDeviceList += `<hr>${device.productName}</hr>`
|
||||
})
|
||||
document.getElementById('granted-devices').innerHTML = grantedDeviceList
|
||||
const grantedDevices2 = await navigator.hid.requestDevice({
|
||||
filters: []
|
||||
})
|
||||
|
||||
grantedDeviceList = ''
|
||||
grantedDevices2.forEach(device => {
|
||||
grantedDeviceList += `<hr>${device.productName}</hr>`
|
||||
})
|
||||
document.getElementById('granted-devices2').innerHTML = grantedDeviceList
|
||||
}
|
||||
|
||||
document.getElementById('clickme').addEventListener('click',testIt)
|
||||
@@ -1,16 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
|
||||
<title>Web Serial API</title>
|
||||
<body>
|
||||
<h1>Web Serial API</h1>
|
||||
|
||||
<button id="clickme">Test Web Serial API</button>
|
||||
|
||||
<p>Matching Arduino Uno device: <strong id="device-name""></strong></p>
|
||||
|
||||
<script src="./renderer.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,54 +0,0 @@
|
||||
const {app, BrowserWindow} = require('electron')
|
||||
const path = require('path')
|
||||
|
||||
function createWindow () {
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 800,
|
||||
height: 600
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
|
||||
event.preventDefault()
|
||||
if (portList && portList.length > 0) {
|
||||
callback(portList[0].portId)
|
||||
} else {
|
||||
callback('') //Could not find any matching devices
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.on('serial-port-added', (event, port) => {
|
||||
console.log('serial-port-added FIRED WITH', port)
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.on('serial-port-removed', (event, port) => {
|
||||
console.log('serial-port-removed FIRED WITH', port)
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
|
||||
if (permission === 'serial' && details.securityOrigin === 'file:///') {
|
||||
return true
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.webContents.session.setDevicePermissionHandler((details) => {
|
||||
if (details.deviceType === 'serial' && details.origin === 'file://') {
|
||||
return true
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.loadFile('index.html')
|
||||
|
||||
mainWindow.webContents.openDevTools()
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
createWindow()
|
||||
|
||||
app.on('activate', function () {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createWindow()
|
||||
})
|
||||
})
|
||||
|
||||
app.on('window-all-closed', function () {
|
||||
if (process.platform !== 'darwin') app.quit()
|
||||
})
|
||||
@@ -1,19 +0,0 @@
|
||||
async function testIt() {
|
||||
const filters = [
|
||||
{ usbVendorId: 0x2341, usbProductId: 0x0043 },
|
||||
{ usbVendorId: 0x2341, usbProductId: 0x0001 }
|
||||
];
|
||||
try {
|
||||
const port = await navigator.serial.requestPort({filters});
|
||||
const portInfo = port.getInfo();
|
||||
document.getElementById('device-name').innerHTML = `vendorId: ${portInfo.usbVendorId} | productId: ${portInfo.usbProductId} `
|
||||
} catch (ex) {
|
||||
if (ex.name === 'NotFoundError') {
|
||||
document.getElementById('device-name').innerHTML = 'Device NOT found'
|
||||
} else {
|
||||
document.getElementById('device-name').innerHTML = ex
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('clickme').addEventListener('click',testIt)
|
||||
@@ -1,5 +1,5 @@
|
||||
// Modules to control application life and create native browser window
|
||||
const { app, BrowserWindow, ipcMain, shell, dialog } = require('electron')
|
||||
const { app, BrowserWindow, ipcMain, shell } = require('electron')
|
||||
const path = require('path')
|
||||
|
||||
let mainWindow;
|
||||
|
||||
118
docs/glossary.md
118
docs/glossary.md
@@ -4,39 +4,15 @@ This page defines some terminology that is commonly used in Electron development
|
||||
|
||||
### ASAR
|
||||
|
||||
ASAR stands for Atom Shell Archive Format. An [asar] archive is a simple
|
||||
ASAR stands for Atom Shell Archive Format. An [asar][asar] archive is a simple
|
||||
`tar`-like format that concatenates files into a single file. Electron can read
|
||||
arbitrary files from it without unpacking the whole file.
|
||||
|
||||
The ASAR format was created primarily to improve performance on Windows when
|
||||
reading large quantities of small files (e.g. when loading your app's JavaScript
|
||||
dependency tree from `node_modules`).
|
||||
|
||||
### code signing
|
||||
|
||||
Code signing is a process where an app developer digitally signs their code to
|
||||
ensure that it hasn't been tampered with after packaging. Both Windows and
|
||||
macOS implement their own version of code signing. As a desktop app developer,
|
||||
it's important that you sign your code if you plan on distributing it to the
|
||||
general public.
|
||||
|
||||
For more information, read the [Code Signing] tutorial.
|
||||
|
||||
### context isolation
|
||||
|
||||
Context isolation is a security measure in Electron that ensures that your
|
||||
preload script cannot leak privileged Electron or Node.js APIs to the web
|
||||
contents in your renderer process. With context isolation enabled, the
|
||||
only way to expose APIs from your preload script is through the
|
||||
`contextBridge` API.
|
||||
|
||||
For more information, read the [Context Isolation] tutorial.
|
||||
|
||||
See also: [preload script](#preload-script), [renderer process](#renderer-process)
|
||||
The ASAR format was created primarily to improve performance on Windows... TODO
|
||||
|
||||
### CRT
|
||||
|
||||
The C Runtime Library (CRT) is the part of the C++ Standard Library that
|
||||
The C Run-time Library (CRT) is the part of the C++ Standard Library that
|
||||
incorporates the ISO C99 standard library. The Visual C++ libraries that
|
||||
implement the CRT support native code development, and both mixed native and
|
||||
managed code, and pure managed code for .NET development.
|
||||
@@ -44,7 +20,8 @@ managed code, and pure managed code for .NET development.
|
||||
### DMG
|
||||
|
||||
An Apple Disk Image is a packaging format used by macOS. DMG files are
|
||||
commonly used for distributing application "installers".
|
||||
commonly used for distributing application "installers". [electron-builder]
|
||||
supports `dmg` as a build target.
|
||||
|
||||
### IME
|
||||
|
||||
@@ -54,15 +31,19 @@ keyboards to input Chinese, Japanese, Korean and Indic characters.
|
||||
|
||||
### IDL
|
||||
|
||||
Interface description language. Write function signatures and data types in a
|
||||
format that can be used to generate interfaces in Java, C++, JavaScript, etc.
|
||||
Interface description language. Write function signatures and data types in a format that can be used to generate interfaces in Java, C++, JavaScript, etc.
|
||||
|
||||
### IPC
|
||||
|
||||
IPC stands for inter-process communication. Electron uses IPC to send
|
||||
serialized JSON messages between the main and renderer processes.
|
||||
IPC stands for Inter-Process Communication. Electron uses IPC to send
|
||||
serialized JSON messages between the [main] and [renderer] processes.
|
||||
|
||||
see also: [main process](#main-process), [renderer process](#renderer-process)
|
||||
### libchromiumcontent
|
||||
|
||||
A shared library that includes the [Chromium Content module] and all its
|
||||
dependencies (e.g., Blink, [V8], etc.). Also referred to as "libcc".
|
||||
|
||||
- [github.com/electron/libchromiumcontent](https://github.com/electron/libchromiumcontent)
|
||||
|
||||
### main process
|
||||
|
||||
@@ -87,22 +68,10 @@ MAS, see the [Mac App Store Submission Guide].
|
||||
|
||||
### Mojo
|
||||
|
||||
An IPC system for communicating intra- or inter-process, and that's important
|
||||
because Chrome is keen on being able to split its work into separate processes
|
||||
or not, depending on memory pressures etc.
|
||||
An IPC system for communicating intra- or inter-process, and that's important because Chrome is keen on being able to split its work into separate processes or not, depending on memory pressures etc.
|
||||
|
||||
See https://chromium.googlesource.com/chromium/src/+/master/mojo/README.md
|
||||
|
||||
See also: [IPC](#ipc)
|
||||
|
||||
### MSI
|
||||
|
||||
On Windows, MSI packages are used by the Windows Installer
|
||||
(also known as Microsoft Installer) service to install and configure
|
||||
applications.
|
||||
|
||||
More information can be found in [Microsoft's documentation][msi].
|
||||
|
||||
### native modules
|
||||
|
||||
Native modules (also called [addons] in
|
||||
@@ -116,33 +85,22 @@ likely to use a different V8 version from the Node binary installed in your
|
||||
system, you have to manually specify the location of Electron’s headers when
|
||||
building native modules.
|
||||
|
||||
For more information, read the [Native Node Modules] tutorial.
|
||||
See also [Using Native Node Modules].
|
||||
|
||||
### notarization
|
||||
### NSIS
|
||||
|
||||
Notarization is a macOS-specific process where a developer can send a
|
||||
code-signed app to Apple servers to get verified for malicious
|
||||
components through an automated service.
|
||||
|
||||
See also: [code signing](#code-signing)
|
||||
Nullsoft Scriptable Install System is a script-driven Installer
|
||||
authoring tool for Microsoft Windows. It is released under a combination of
|
||||
free software licenses, and is a widely-used alternative to commercial
|
||||
proprietary products like InstallShield. [electron-builder] supports NSIS
|
||||
as a build target.
|
||||
|
||||
### OSR
|
||||
|
||||
OSR (offscreen rendering) can be used for loading heavy page in
|
||||
OSR (Off-screen rendering) can be used for loading heavy page in
|
||||
background and then displaying it after (it will be much faster).
|
||||
It allows you to render page without showing it on screen.
|
||||
|
||||
For more information, read the [Offscreen Rendering][osr] tutorial.
|
||||
|
||||
### preload script
|
||||
|
||||
Preload scripts contain code that executes in a renderer process
|
||||
before its web contents begin loading. These scripts run within
|
||||
the renderer context, but are granted more privileges by having
|
||||
access to Node.js APIs.
|
||||
|
||||
See also: [renderer process](#renderer-process), [context isolation](#context-isolation)
|
||||
|
||||
### process
|
||||
|
||||
A process is an instance of a computer program that is being executed. Electron
|
||||
@@ -162,17 +120,13 @@ The renderer process is a browser window in your app. Unlike the main process,
|
||||
there can be multiple of these and each is run in a separate process.
|
||||
They can also be hidden.
|
||||
|
||||
In normal browsers, web pages usually run in a sandboxed environment and are not
|
||||
allowed access to native resources. Electron users, however, have the power to
|
||||
use Node.js APIs in web pages allowing lower level operating system
|
||||
interactions.
|
||||
|
||||
See also: [process](#process), [main process](#main-process)
|
||||
|
||||
### sandbox
|
||||
|
||||
The sandbox is a security feature inherited from Chromium that restricts
|
||||
your renderer processes to a limited set of permissions.
|
||||
|
||||
For more information, read the [Process Sandboxing] tutorial.
|
||||
|
||||
See also: [process](#process)
|
||||
|
||||
### Squirrel
|
||||
|
||||
Squirrel is an open-source framework that enables Electron apps to update
|
||||
@@ -220,15 +174,13 @@ embedded content.
|
||||
|
||||
[addons]: https://nodejs.org/api/addons.html
|
||||
[asar]: https://github.com/electron/asar
|
||||
[autoupdater]: api/auto-updater.md
|
||||
[code signing]: tutorial/code-signing.md
|
||||
[context isolation]: tutorial/context-isolation.md
|
||||
[mac app store submission guide]: tutorial/mac-app-store-submission-guide.md
|
||||
[autoUpdater]: api/auto-updater.md
|
||||
[Chromium Content module]: https://www.chromium.org/developers/content-module
|
||||
[electron-builder]: https://github.com/electron-userland/electron-builder
|
||||
[libchromiumcontent]: #libchromiumcontent
|
||||
[Mac App Store Submission Guide]: tutorial/mac-app-store-submission-guide.md
|
||||
[main]: #main-process
|
||||
[msi]: https://docs.microsoft.com/en-us/windows/win32/msi/windows-installer-portal
|
||||
[offscreen rendering]: tutorial/offscreen-rendering.md
|
||||
[process sandboxing]: tutorial/sandbox.md
|
||||
[renderer]: #renderer-process
|
||||
[userland]: #userland
|
||||
[using native node modules]: tutorial/using-native-node-modules.md
|
||||
[v8]: #v8
|
||||
[Using Native Node Modules]: tutorial/using-native-node-modules.md
|
||||
[V8]: #v8
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 19 KiB |
@@ -45,4 +45,4 @@ If the V8 context crashes, the DevTools will display this message.
|
||||
|
||||
Chromium logs can be enabled via the `ELECTRON_ENABLE_LOGGING` environment variable. For more information, see the [environment variables documentation](../api/environment-variables.md#electron_enable_logging).
|
||||
|
||||
Alternatively, the command line argument `--enable-logging` can be passed. More information is available in the [command line switches documentation](../api/command-line-switches.md#--enable-loggingfile).
|
||||
Alternatively, the command line argument `--enable-logging` can be passed. More information is available in the [command line switches documentation](../api/command-line-switches.md#--enable-logging).
|
||||
|
||||
@@ -56,7 +56,7 @@ will then be your distribution to deliver to users.
|
||||
|
||||
### With an app source code archive
|
||||
|
||||
Instead of shipping your app by copying all of its source files, you can
|
||||
Instead of from shipping your app by copying all of its source files, you can
|
||||
package your app into an [asar] archive to improve the performance of reading
|
||||
files on platforms like Windows, if you are not already using a bundler such
|
||||
as Parcel or Webpack.
|
||||
|
||||
@@ -192,6 +192,7 @@ it may be worth your time to shop around. Popular resellers include:
|
||||
|
||||
* [digicert](https://www.digicert.com/code-signing/microsoft-authenticode.htm)
|
||||
* [Sectigo](https://sectigo.com/ssl-certificates-tls/code-signing)
|
||||
* [GoDaddy](https://au.godaddy.com/web-security/code-signing-certificate)
|
||||
* Amongst others, please shop around to find one that suits your needs, Google
|
||||
is your friend 😄
|
||||
|
||||
|
||||
@@ -4,38 +4,39 @@
|
||||
|
||||
Context Isolation is a feature that ensures that both your `preload` scripts and Electron's internal logic run in a separate context to the website you load in a [`webContents`](../api/web-contents.md). This is important for security purposes as it helps prevent the website from accessing Electron internals or the powerful APIs your preload script has access to.
|
||||
|
||||
This means that the `window` object that your preload script has access to is actually a **different** object than the website would have access to. For example, if you set `window.hello = 'wave'` in your preload script and context isolation is enabled, `window.hello` will be undefined if the website tries to access it.
|
||||
This means that the `window` object that your preload script has access to is actually a **different** object than the website would have access to. For example, if you set `window.hello = 'wave'` in your preload script and context isolation is enabled `window.hello` will be undefined if the website tries to access it.
|
||||
|
||||
Context isolation has been enabled by default since Electron 12, and it is a recommended security setting for _all applications_.
|
||||
Every single application should have context isolation enabled and from Electron 12 it will be enabled by default.
|
||||
|
||||
## How do I enable it?
|
||||
|
||||
From Electron 12, it will be enabled by default. For lower versions it is an option in the `webPreferences` option when constructing `new BrowserWindow`'s.
|
||||
|
||||
```javascript
|
||||
const mainWindow = new BrowserWindow({
|
||||
webPreferences: {
|
||||
contextIsolation: true
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Migration
|
||||
|
||||
> Without context isolation, I used to provide APIs from my preload script using `window.X = apiObject`. Now what?
|
||||
> I used to provide APIs from my preload script using `window.X = apiObject` now what?
|
||||
|
||||
### Before: context isolation disabled
|
||||
Exposing APIs from your preload script to the loaded website is a common usecase and there is a dedicated module in Electron to help you do this in a painless way.
|
||||
|
||||
Exposing APIs from your preload script to a loaded website in the renderer process is a common use-case. With context isolation disabled, your preload script would share a common global `window` object with the renderer. You could then attach arbitrary properties to a preload script:
|
||||
**Before: With context isolation disabled**
|
||||
|
||||
```javascript title='preload.js'
|
||||
// preload with contextIsolation disabled
|
||||
```javascript
|
||||
window.myAPI = {
|
||||
doAThing: () => {}
|
||||
}
|
||||
```
|
||||
|
||||
The `doAThing()` function could then be used directly in the renderer process:
|
||||
**After: With context isolation enabled**
|
||||
|
||||
```javascript title='renderer.js'
|
||||
// use the exposed API in the renderer
|
||||
window.myAPI.doAThing()
|
||||
```
|
||||
|
||||
### After: context isolation enabled
|
||||
|
||||
There is a dedicated module in Electron to help you do this in a painless way. The [`contextBridge`](../api/context-bridge.md) module can be used to **safely** expose APIs from your preload script's isolated context to the context the website is running in. The API will also be accessible from the website on `window.myAPI` just like it was before.
|
||||
|
||||
```javascript title='preload.js'
|
||||
// preload with contextIsolation enabled
|
||||
```javascript
|
||||
const { contextBridge } = require('electron')
|
||||
|
||||
contextBridge.exposeInMainWorld('myAPI', {
|
||||
@@ -43,63 +44,26 @@ contextBridge.exposeInMainWorld('myAPI', {
|
||||
})
|
||||
```
|
||||
|
||||
```javascript title='renderer.js'
|
||||
// use the exposed API in the renderer
|
||||
window.myAPI.doAThing()
|
||||
```
|
||||
The [`contextBridge`](../api/context-bridge.md) module can be used to **safely** expose APIs from the isolated context your preload script runs in to the context the website is running in. The API will also be accessible from the website on `window.myAPI` just like it was before.
|
||||
|
||||
Please read the `contextBridge` documentation linked above to fully understand its limitations. For instance, you can't send custom prototypes or symbols over the bridge.
|
||||
You should read the `contextBridge` documentation linked above to fully understand its limitations. For instance you can't send custom prototypes or symbols over the bridge.
|
||||
|
||||
## Security considerations
|
||||
## Security Considerations
|
||||
|
||||
Just enabling `contextIsolation` and using `contextBridge` does not automatically mean that everything you do is safe. For instance, this code is **unsafe**.
|
||||
Just enabling `contextIsolation` and using `contextBridge` does not automatically mean that everything you do is safe. For instance this code is **unsafe**.
|
||||
|
||||
```javascript title='preload.js'
|
||||
```javascript
|
||||
// ❌ Bad code
|
||||
contextBridge.exposeInMainWorld('myAPI', {
|
||||
send: ipcRenderer.send
|
||||
})
|
||||
```
|
||||
|
||||
It directly exposes a powerful API without any kind of argument filtering. This would allow any website to send arbitrary IPC messages, which you do not want to be possible. The correct way to expose IPC-based APIs would instead be to provide one method per IPC message.
|
||||
It directly exposes a powerful API without any kind of argument filtering. This would allow any website to send arbitrary IPC messages which you do not want to be possible. The correct way to expose IPC-based APIs would instead be to provide one method per IPC message.
|
||||
|
||||
```javascript title='preload.js'
|
||||
```javascript
|
||||
// ✅ Good code
|
||||
contextBridge.exposeInMainWorld('myAPI', {
|
||||
loadPreferences: () => ipcRenderer.invoke('load-prefs')
|
||||
})
|
||||
```
|
||||
|
||||
## Usage with TypeScript
|
||||
|
||||
If you're building your Electron app with TypeScript, you'll want to add types to your APIs exposed over the context bridge. The renderer's `window` object won't have the correct typings unless you extend the types with a [declaration file].
|
||||
|
||||
For example, given this `preload.ts` script:
|
||||
|
||||
```typescript title='preload.ts'
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
loadPreferences: () => ipcRenderer.invoke('load-prefs')
|
||||
})
|
||||
```
|
||||
|
||||
You can create a `renderer.d.ts` declaration file and globally augment the `Window` interface:
|
||||
|
||||
```typescript title='renderer.d.ts'
|
||||
export interface IElectronAPI {
|
||||
loadPreferences: () => Promise<void>,
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
electronAPI: IElectronAPI
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Doing so will ensure that the TypeScript compiler will know about the `electronAPI` property on your global `window` object when writing scripts in your renderer process:
|
||||
|
||||
```typescript title='renderer.ts'
|
||||
window.electronAPI.loadPreferences()
|
||||
```
|
||||
|
||||
[declaration file]: https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html
|
||||
|
||||
@@ -80,9 +80,9 @@ Starting with the `index.html` file:
|
||||
</html>
|
||||
```
|
||||
|
||||
And the `styles.css` file:
|
||||
And the `style.css` file:
|
||||
|
||||
```css title='styles.css'
|
||||
```css title='style.css'
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { background: #333; color: white; }
|
||||
}
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
# Device Access
|
||||
|
||||
Like Chromium based browsers, Electron provides access to device hardware
|
||||
through web APIs. For the most part these APIs work like they do in a browser,
|
||||
but there are some differences that need to be taken into account. The primary
|
||||
difference between Electron and browsers is what happens when device access is
|
||||
requested. In a browser, users are presented with a popup where they can grant
|
||||
access to an individual device. In Electron APIs are provided which can be
|
||||
used by a developer to either automatically pick a device or prompt users to
|
||||
pick a device via a developer created interface.
|
||||
|
||||
## Web Bluetooth API
|
||||
|
||||
The [Web Bluetooth API](https://web.dev/bluetooth/) can be used to communicate
|
||||
with bluetooth devices. In order to use this API in Electron, developers will
|
||||
need to handle the [`select-bluetooth-device` event on the webContents](../api/web-contents.md#event-select-bluetooth-device)
|
||||
associated with the device request.
|
||||
|
||||
### Example
|
||||
|
||||
This example demonstrates an Electron application that automatically selects
|
||||
the first available bluetooth device when the `Test Bluetooth` button is
|
||||
clicked.
|
||||
|
||||
```javascript fiddle='docs/fiddles/features/web-bluetooth'
|
||||
|
||||
```
|
||||
|
||||
## WebHID API
|
||||
|
||||
The [WebHID API](https://web.dev/hid/) can be used to access HID devices such
|
||||
as keyboards and gamepads. Electron provides several APIs for working with
|
||||
the WebHID API:
|
||||
|
||||
* The [`select-hid-device` event on the Session](../api/session.md#event-select-hid-device)
|
||||
can be used to select a HID device when a call to
|
||||
`navigator.hid.requestDevice` is made. Additionally the [`hid-device-added`](../api/session.md#event-hid-device-added)
|
||||
and [`hid-device-removed`](../api/session.md#event-hid-device-removed) events
|
||||
on the Session can be used to handle devices being plugged in or unplugged during the
|
||||
`navigator.hid.requestDevice` process.
|
||||
* [`ses.setDevicePermissionHandler(handler)`](../api/session.md#sessetdevicepermissionhandlerhandler)
|
||||
can be used to provide default permissioning to devices without first calling
|
||||
for permission to devices via `navigator.hid.requestDevice`. Additionally,
|
||||
the default behavior of Electron is to store granted device permision through
|
||||
the lifetime of the corresponding WebContents. If longer term storage is
|
||||
needed, a developer can store granted device permissions (eg when handling
|
||||
the `select-hid-device` event) and then read from that storage with
|
||||
`setDevicePermissionHandler`.
|
||||
* [`ses.setPermissionCheckHandler(handler)`](../api/session.md#sessetpermissioncheckhandlerhandler)
|
||||
can be used to disable HID access for specific origins.
|
||||
|
||||
### Blocklist
|
||||
|
||||
By default Electron employs the same [blocklist](https://github.com/WICG/webhid/blob/main/blocklist.txt)
|
||||
used by Chromium. If you wish to override this behavior, you can do so by
|
||||
setting the `disable-hid-blocklist` flag:
|
||||
|
||||
```javascript
|
||||
app.commandLine.appendSwitch('disable-hid-blocklist')
|
||||
```
|
||||
|
||||
### Example
|
||||
|
||||
This example demonstrates an Electron application that automatically selects
|
||||
HID devices through [`ses.setDevicePermissionHandler(handler)`](../api/session.md#sessetdevicepermissionhandlerhandler)
|
||||
and through [`select-hid-device` event on the Session](../api/session.md#event-select-hid-device)
|
||||
when the `Test WebHID` button is clicked.
|
||||
|
||||
```javascript fiddle='docs/fiddles/features/web-hid'
|
||||
|
||||
```
|
||||
|
||||
## Web Serial API
|
||||
|
||||
The [Web Serial API](https://web.dev/serial/) can be used to access serial
|
||||
devices that are connected via serial port, USB, or Bluetooth. In order to use
|
||||
this API in Electron, developers will need to handle the
|
||||
[`select-serial-port` event on the Session](../api/session.md#event-select-serial-port)
|
||||
associated with the serial port request.
|
||||
|
||||
There are several additional APIs for working with the Web Serial API:
|
||||
|
||||
* The [`serial-port-added`](../api/session.md#event-serial-port-added)
|
||||
and [`serial-port-removed`](../api/session.md#event-serial-port-removed) events
|
||||
on the Session can be used to handle devices being plugged in or unplugged during the
|
||||
`navigator.serial.requestPort` process.
|
||||
* [`ses.setDevicePermissionHandler(handler)`](../api/session.md#sessetdevicepermissionhandlerhandler)
|
||||
can be used to provide default permissioning to devices without first calling
|
||||
for permission to devices via `navigator.serial.requestPort`. Additionally,
|
||||
the default behavior of Electron is to store granted device permision through
|
||||
the lifetime of the corresponding WebContents. If longer term storage is
|
||||
needed, a developer can store granted device permissions (eg when handling
|
||||
the `select-serial-port` event) and then read from that storage with
|
||||
`setDevicePermissionHandler`.
|
||||
* [`ses.setPermissionCheckHandler(handler)`](../api/session.md#sessetpermissioncheckhandlerhandler)
|
||||
can be used to disable serial access for specific origins.
|
||||
|
||||
### Example
|
||||
|
||||
This example demonstrates an Electron application that automatically selects
|
||||
serial devices through [`ses.setDevicePermissionHandler(handler)`](../api/session.md#sessetdevicepermissionhandlerhandler)
|
||||
as well as demonstrating selecting the first available Arduino Uno serial device (if connected) through
|
||||
[`select-serial-port` event on the Session](../api/session.md#event-select-serial-port)
|
||||
when the `Test Web Serial` button is clicked.
|
||||
|
||||
```javascript fiddle='docs/fiddles/features/web-serial'
|
||||
|
||||
```
|
||||
@@ -23,6 +23,5 @@ Special notes:
|
||||
| 11.0.0 | -- | 2020-Aug-27 | 2020-Nov-17 | M87 | v12.18 |
|
||||
| 12.0.0 | -- | 2020-Nov-19 | 2021-Mar-02 | M89 | v14.16 |
|
||||
| 13.0.0 | -- | 2021-Mar-04 | 2021-May-25 | M91 | v14.16 |
|
||||
| 14.0.0 | -- | 2021-May-27 | 2021-Aug-31 | M93 | v14.17 |
|
||||
| 15.0.0 | 2021-Jul-20 | 2021-Sep-01 | 2021-Sep-21 | M94 | v16.5 |
|
||||
| 16.0.0 | -- | 2021-Sep-23 | 2021-Nov-16 | M96 | TBD |
|
||||
| 14.0.0 | -- | 2021-May-27 | 2021-Aug-31 | M93 | TBD |
|
||||
| 15.0.0 | 2021-Jul-20 | 2021-Sep-01 | 2021-Sep-21 | M94 | TBD |
|
||||
|
||||
@@ -2,31 +2,43 @@
|
||||
|
||||
> A detailed look at our versioning policy and implementation.
|
||||
|
||||
As of version 2.0.0, Electron follows the [SemVer](#semver) spec. The following command will install the most recent stable build of Electron:
|
||||
As of version 2.0.0, Electron follows [SemVer](#semver). The following command will install the most recent stable build of Electron:
|
||||
|
||||
```sh npm2yarn
|
||||
```sh
|
||||
npm install --save-dev electron
|
||||
```
|
||||
|
||||
To update an existing project to use the latest stable version:
|
||||
|
||||
```sh npm2yarn
|
||||
```sh
|
||||
npm install --save-dev electron@latest
|
||||
```
|
||||
|
||||
## Versioning scheme
|
||||
## Version 1.x
|
||||
|
||||
Electron versions *< 2.0* did not conform to the [SemVer](https://semver.org) spec: major versions corresponded to end-user API changes, minor versions corresponded to Chromium major releases, and patch versions corresponded to new features and bug fixes. While convenient for developers merging features, it creates problems for developers of client-facing applications. The QA testing cycles of major apps like Slack, Stride, Teams, Skype, VS Code, Atom, and Desktop can be lengthy and stability is a highly desired outcome. There is a high risk in adopting new features while trying to absorb bug fixes.
|
||||
|
||||
Here is an example of the 1.x strategy:
|
||||
|
||||

|
||||
|
||||
An app developed with `1.8.1` cannot take the `1.8.3` bug fix without either absorbing the `1.8.2` feature, or by backporting the fix and maintaining a new release line.
|
||||
|
||||
## Version 2.0 and Beyond
|
||||
|
||||
There are several major changes from our 1.x strategy outlined below. Each change is intended to satisfy the needs and priorities of developers/maintainers and app developers.
|
||||
|
||||
1. Strict use of the [SemVer](#semver) spec
|
||||
1. Strict use of SemVer
|
||||
2. Introduction of semver-compliant `-beta` tags
|
||||
3. Introduction of [conventional commit messages](https://conventionalcommits.org/)
|
||||
4. Well-defined stabilization branches
|
||||
5. The `main` branch is versionless; only stabilization branches contain version information
|
||||
5. The `master` branch is versionless; only stabilization branches contain version information
|
||||
|
||||
We will cover in detail how git branching works, how npm tagging works, what developers should expect to see, and how one can backport changes.
|
||||
|
||||
## SemVer
|
||||
# SemVer
|
||||
|
||||
From 2.0 onward, Electron will follow SemVer.
|
||||
|
||||
Below is a table explicitly mapping types of changes to their corresponding category of SemVer (e.g. Major, Minor, Patch).
|
||||
|
||||
@@ -36,25 +48,22 @@ Below is a table explicitly mapping types of changes to their corresponding cate
|
||||
| Node.js major version updates | Node.js minor version updates | Node.js patch version updates |
|
||||
| Chromium version updates | | fix-related chromium patches |
|
||||
|
||||
For more information, see the [Semantic Versioning 2.0.0](https://semver.org/) spec.
|
||||
|
||||
Note that most Chromium updates will be considered breaking. Fixes that can be backported will likely be cherry-picked as patches.
|
||||
|
||||
## Stabilization branches
|
||||
# Stabilization Branches
|
||||
|
||||
Stabilization branches are branches that run parallel to `main`, taking in only cherry-picked commits that are related to security or stability. These branches are never merged back to `main`.
|
||||
Stabilization branches are branches that run parallel to master, taking in only cherry-picked commits that are related to security or stability. These branches are never merged back to master.
|
||||
|
||||

|
||||
|
||||
Since Electron 8, stabilization branches are always **major** version lines, and named against the following template `$MAJOR-x-y` e.g. `8-x-y`. Prior to that we used **minor** version lines and named them as `$MAJOR-$MINOR-x` e.g. `2-0-x`.
|
||||
|
||||
We allow for multiple stabilization branches to exist simultaneously, one for each supported version. For more details on which versions are supported, see our [Electron Release Timelines](./electron-timelines.md) doc.
|
||||
Since Electron 8, stabilization branches are always **major** version lines, and named against the following template `$MAJOR-x-y` e.g. `8-x-y`. Prior to that we used **minor** version lines and named them as `$MAJOR-$MINOR-x` e.g. `2-0-x`
|
||||
|
||||
We allow for multiple stabilization branches to exist simultaneously, and intend to support at least two in parallel at all times, backporting security fixes as necessary.
|
||||

|
||||
|
||||
Older lines will not be supported by the Electron project, but other groups can take ownership and backport stability and security fixes on their own. We discourage this, but recognize that it makes life easier for many app developers.
|
||||
Older lines will not be supported by GitHub, but other groups can take ownership and backport stability and security fixes on their own. We discourage this, but recognize that it makes life easier for many app developers.
|
||||
|
||||
## Beta releases and bug fixes
|
||||
# Beta Releases and Bug Fixes
|
||||
|
||||
Developers want to know which releases are _safe_ to use. Even seemingly innocent features can introduce regressions in complex applications. At the same time, locking to a fixed version is dangerous because you’re ignoring security patches and bug fixes that may have come out since your version. Our goal is to allow the following standard semver ranges in `package.json` :
|
||||
|
||||
@@ -107,7 +116,15 @@ A few examples of how various SemVer ranges will pick up new releases:
|
||||
|
||||

|
||||
|
||||
## Feature flags
|
||||
# Missing Features: Alphas
|
||||
|
||||
Our strategy has a few tradeoffs, which for now we feel are appropriate. Most importantly that new features in master may take a while before reaching a stable release line. If you want to try a new feature immediately, you will have to build Electron yourself.
|
||||
|
||||
As a future consideration, we may introduce one or both of the following:
|
||||
|
||||
* alpha releases that have looser stability constraints to betas; for example it would be allowable to admit new features while a stability channel is in _alpha_
|
||||
|
||||
# Feature Flags
|
||||
|
||||
Feature flags are a common practice in Chromium, and are well-established in the web-development ecosystem. In the context of Electron, a feature flag or **soft branch** must have the following properties:
|
||||
|
||||
@@ -115,29 +132,20 @@ Feature flags are a common practice in Chromium, and are well-established in the
|
||||
* it completely segments new and old code paths; refactoring old code to support a new feature _violates_ the feature-flag contract
|
||||
* feature flags are eventually removed after the feature is released
|
||||
|
||||
## Semantic commits
|
||||
# Semantic Commits
|
||||
|
||||
All pull requests must adhere to the [Conventional Commits](https://conventionalcommits.org/) spec, which can be summarized as follows:
|
||||
We seek to increase clarity at all levels of the update and releases process. Starting with `2.0.0` we will require pull requests adhere to the [Conventional Commits](https://conventionalcommits.org/) spec, which can be summarized as follows:
|
||||
|
||||
* Commits that would result in a SemVer **major** bump must start their body with `BREAKING CHANGE:`.
|
||||
* Commits that would result in a SemVer **minor** bump must start with `feat:`.
|
||||
* Commits that would result in a SemVer **patch** bump must start with `fix:`.
|
||||
|
||||
The `electron/electron` repository also enforces squash merging, so you only need to make sure that your pull request has the correct title prefix.
|
||||
* We allow squashing of commits, provided that the squashed message adheres to the above message format.
|
||||
* It is acceptable for some commits in a pull request to not include a semantic prefix, as long as the pull request title contains a meaningful encompassing semantic message.
|
||||
|
||||
## Versioned `main` branch
|
||||
# Versioned `master`
|
||||
|
||||
* The `main` branch will always contain the next major version `X.0.0-nightly.DATE` in its `package.json`.
|
||||
* Release branches are never merged back to `main`.
|
||||
* Release branches _do_ contain the correct version in their `package.json`.
|
||||
* As soon as a release branch is cut for a major, `main` must be bumped to the next major (i.e. `main` is always versioned as the next theoretical release branch).
|
||||
|
||||
## Historical versioning (Electron 1.X)
|
||||
|
||||
Electron versions *< 2.0* did not conform to the [SemVer](https://semver.org) spec: major versions corresponded to end-user API changes, minor versions corresponded to Chromium major releases, and patch versions corresponded to new features and bug fixes. While convenient for developers merging features, it creates problems for developers of client-facing applications. The QA testing cycles of major apps like Slack, Teams, Skype, VS Code, and GitHub Desktop can be lengthy and stability is a highly desired outcome. There is a high risk in adopting new features while trying to absorb bug fixes.
|
||||
|
||||
Here is an example of the 1.x strategy:
|
||||
|
||||

|
||||
|
||||
An app developed with `1.8.1` cannot take the `1.8.3` bug fix without either absorbing the `1.8.2` feature, or by backporting the fix and maintaining a new release line.
|
||||
* The `master` branch will always contain the next major version `X.0.0-nightly.DATE` in its `package.json`
|
||||
* Release branches are never merged back to master
|
||||
* Release branches _do_ contain the correct version in their `package.json`
|
||||
* As soon as a release branch is cut for a major, master must be bumped to the next major. I.e. `master` is always versioned as the next theoretical release branch
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Launching Your Electron App From a URL In Another App
|
||||
title: launch-app-from-URL-in-another-app
|
||||
description: This guide will take you through the process of setting your electron app as the default handler for a specific protocol.
|
||||
slug: launch-app-from-url-in-another-app
|
||||
hide_title: true
|
||||
@@ -11,7 +11,7 @@ hide_title: true
|
||||
|
||||
<!-- ✍ Update this section if you want to provide more details -->
|
||||
|
||||
This guide will take you through the process of setting your Electron app as the default
|
||||
This guide will take you through the process of setting your electron app as the default
|
||||
handler for a specific [protocol](https://www.electronjs.org/docs/api/protocol).
|
||||
|
||||
By the end of this tutorial, we will have set our app to intercept and handle
|
||||
@@ -22,17 +22,16 @@ we will use will be "`electron-fiddle://`".
|
||||
|
||||
### Main Process (main.js)
|
||||
|
||||
First, we will import the required modules from `electron`. These modules help
|
||||
control our application lifecycle and create a native browser window.
|
||||
First we will import the required modules from `electron`. These modules help control our application life and create a native browser window.
|
||||
|
||||
```javascript
|
||||
```js
|
||||
const { app, BrowserWindow, shell } = require('electron')
|
||||
const path = require('path')
|
||||
```
|
||||
|
||||
Next, we will proceed to register our application to handle all "`electron-fiddle://`" protocols.
|
||||
|
||||
```javascript
|
||||
```js
|
||||
if (process.defaultApp) {
|
||||
if (process.argv.length >= 2) {
|
||||
app.setAsDefaultProtocolClient('electron-fiddle', process.execPath, [path.resolve(process.argv[1])])
|
||||
@@ -44,8 +43,8 @@ if (process.defaultApp) {
|
||||
|
||||
We will now define the function in charge of creating our browser window and load our application's `index.html` file.
|
||||
|
||||
```javascript
|
||||
const createWindow = () => {
|
||||
```js
|
||||
function createWindow () {
|
||||
// Create the browser window.
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 800,
|
||||
@@ -61,11 +60,11 @@ const createWindow = () => {
|
||||
|
||||
In this next step, we will create our `BrowserWindow` and tell our application how to handle an event in which an external protocol is clicked.
|
||||
|
||||
This code will be different in Windows compared to MacOS and Linux. This is due to Windows requiring additional code in order to open the contents of the protocol link within the same Electron instance. Read more about this [here](https://www.electronjs.org/docs/api/app#apprequestsingleinstancelock).
|
||||
This code will be different in WindowsOS compared to MacOS and Linux. This is due to Windows requiring additional code in order to open the contents of the protocol link within the same electron instance. Read more about this [here](https://www.electronjs.org/docs/api/app#apprequestsingleinstancelock).
|
||||
|
||||
#### Windows code:
|
||||
### Windows code:
|
||||
|
||||
```javascript
|
||||
```js
|
||||
const gotTheLock = app.requestSingleInstanceLock()
|
||||
|
||||
if (!gotTheLock) {
|
||||
@@ -84,16 +83,16 @@ if (!gotTheLock) {
|
||||
createWindow()
|
||||
})
|
||||
|
||||
// Handle the protocol. In this case, we choose to show an Error Box.
|
||||
// handling the protocol. In this case, we choose to show an Error Box.
|
||||
app.on('open-url', (event, url) => {
|
||||
dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
#### MacOS and Linux code:
|
||||
### MacOS and Linux code:
|
||||
|
||||
```javascript
|
||||
```js
|
||||
// This method will be called when Electron has finished
|
||||
// initialization and is ready to create browser windows.
|
||||
// Some APIs can only be used after this event occurs.
|
||||
@@ -101,101 +100,57 @@ app.whenReady().then(() => {
|
||||
createWindow()
|
||||
})
|
||||
|
||||
// Handle the protocol. In this case, we choose to show an Error Box.
|
||||
// handling the protocol. In this case, we choose to show an Error Box.
|
||||
app.on('open-url', (event, url) => {
|
||||
dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
|
||||
})
|
||||
```
|
||||
|
||||
Finally, we will add some additional code to handle when someone closes our application.
|
||||
Finally, we will add some additional code to handle when someone closes our application
|
||||
|
||||
```javascript
|
||||
```js
|
||||
// Quit when all windows are closed, except on macOS. There, it's common
|
||||
// for applications and their menu bar to stay active until the user quits
|
||||
// explicitly with Cmd + Q.
|
||||
app.on('window-all-closed', () => {
|
||||
app.on('window-all-closed', function () {
|
||||
if (process.platform !== 'darwin') app.quit()
|
||||
})
|
||||
```
|
||||
|
||||
## Important notes
|
||||
## Important Note:
|
||||
|
||||
### Packaging
|
||||
|
||||
On macOS and Linux, this feature will only work when your app is packaged. It will not work when
|
||||
you're launching it in development from the command-line. When you package your app you'll need to
|
||||
make sure the macOS `Info.plist` and the Linux `.desktop` files for the app are updated to include
|
||||
the new protocol handler. Some of the Electron tools for bundling and distributing apps handle
|
||||
this for you.
|
||||
This feature will only work on macOS when your app is packaged. It will not work when you're launching it in development from the command-line. When you package your app you'll need to make sure the macOS `plist` for the app is updated to include the new protocol handler. If you're using [`electron-packager`](https://github.com/electron/electron-packager) then you
|
||||
can add the flag `--extend-info` with a path to the `plist` you've created. The one for this app is below:
|
||||
|
||||
#### [Electron Forge](https://electronforge.io)
|
||||
### Plist
|
||||
|
||||
If you're using Electron Forge, adjust `packagerConfig` for macOS support, and the configuration for
|
||||
the appropriate Linux makers for Linux support, in your [Forge
|
||||
configuration](https://www.electronforge.io/configuration) _(please note the following example only
|
||||
shows the bare minimum needed to add the configuration changes)_:
|
||||
|
||||
```json
|
||||
{
|
||||
"config": {
|
||||
"forge": {
|
||||
"packagerConfig": {
|
||||
"protocols": [
|
||||
{
|
||||
"name": "Electron Fiddle",
|
||||
"schemes": ["electron-fiddle"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"makers": [
|
||||
{
|
||||
"name": "@electron-forge/maker-deb",
|
||||
"config": {
|
||||
"mimeType": ["x-scheme-handler/electron-fiddle"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### [Electron Packager](https://github.com/electron/electron-packager)
|
||||
|
||||
For macOS support:
|
||||
|
||||
If you're using Electron Packager's API, adding support for protocol handlers is similar to how
|
||||
Electron Forge is handled, except
|
||||
`protocols` is part of the Packager options passed to the `packager` function.
|
||||
|
||||
```javascript
|
||||
const packager = require('electron-packager')
|
||||
|
||||
packager({
|
||||
// ...other options...
|
||||
protocols: [
|
||||
{
|
||||
name: 'Electron Fiddle',
|
||||
schemes: ['electron-fiddle']
|
||||
}
|
||||
]
|
||||
|
||||
}).then(paths => console.log(`SUCCESS: Created ${paths.join(', ')}`))
|
||||
.catch(err => console.error(`ERROR: ${err.message}`))
|
||||
```
|
||||
|
||||
If you're using Electron Packager's CLI, use the `--protocol` and `--protocol-name` flags. For
|
||||
example:
|
||||
|
||||
```shell
|
||||
npx electron-packager . --protocol=electron-fiddle --protocol-name="Electron Fiddle"
|
||||
```XML
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>electron-api-demos</string>
|
||||
</array>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>Electron API Demos Protocol</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>ElectronTeamID</key>
|
||||
<string>VEKTX9H2N7</string>
|
||||
</dict>
|
||||
</plist>
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
After you start your Electron app, you can enter in a URL in your browser that contains the custom
|
||||
protocol, for example `"electron-fiddle://open"` and observe that the application will respond and
|
||||
show an error dialog box.
|
||||
After you start your electron app, you can now enter in a URL in your browser that contains the custom protocol, for example `"electron-fiddle://open"` and observe that the application will respond and show an error dialog box.
|
||||
|
||||
<!--
|
||||
Because Electron examples usually require multiple files (HTML, CSS, JS
|
||||
|
||||
@@ -120,9 +120,9 @@ file in the directory you executed it in. Both files can be analyzed using
|
||||
the Chrome Developer Tools, using the `Performance` and `Memory` tabs
|
||||
respectively.
|
||||
|
||||

|
||||
![Performance CPU Profile][performance-cpu-prof]
|
||||
|
||||

|
||||
![Performance Heap Memory Profile][performance-heap-prof]
|
||||
|
||||
In this example, on the author's machine, we saw that loading `request` took
|
||||
almost half a second, whereas `node-fetch` took dramatically less memory
|
||||
@@ -412,6 +412,8 @@ As of writing this article, the popular choices include [Webpack][webpack],
|
||||
[Parcel][parcel], and [rollup.js][rollup].
|
||||
|
||||
[security]: ./security.md
|
||||
[performance-cpu-prof]: ../images/performance-cpu-prof.png
|
||||
[performance-heap-prof]: ../images/performance-heap-prof.png
|
||||
[chrome-devtools-tutorial]: https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/
|
||||
[worker-threads]: https://nodejs.org/api/worker_threads.html
|
||||
[web-workers]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
|
||||
|
||||
@@ -83,7 +83,7 @@ As a practical example, the app shown in the [quick start guide][quick-start-lif
|
||||
uses `app` APIs to create a more native application window experience.
|
||||
|
||||
```js title='main.js'
|
||||
// quitting the app when no windows are open on non-macOS platforms
|
||||
// quitting the app when no windows are open on macOS
|
||||
app.on('window-all-closed', function () {
|
||||
if (process.platform !== 'darwin') app.quit()
|
||||
})
|
||||
|
||||
@@ -7,16 +7,16 @@ without the need of switching to the window itself.
|
||||
|
||||
On Windows, you can use a taskbar button to display a progress bar.
|
||||
|
||||

|
||||
![Windows Progress Bar][windows-progress-bar]
|
||||
|
||||
On macOS, the progress bar will be displayed as a part of the dock icon.
|
||||
|
||||

|
||||
![macOS Progress Bar][macos-progress-bar]
|
||||
|
||||
On Linux, the Unity graphical interface also has a similar feature that allows
|
||||
you to specify the progress bar in the launcher.
|
||||
|
||||

|
||||
![Linux Progress Bar][linux-progress-bar]
|
||||
|
||||
> NOTE: on Windows, each window can have its own progress bar, whereas on macOS
|
||||
and Linux (Unity) there can be only one progress bar for the application.
|
||||
@@ -102,4 +102,8 @@ For macOS, the progress bar will also be indicated for your application
|
||||
when using [Mission Control](https://support.apple.com/en-us/HT204100):
|
||||
|
||||

|
||||
|
||||
[windows-progress-bar]: https://cloud.githubusercontent.com/assets/639601/5081682/16691fda-6f0e-11e4-9676-49b6418f1264.png
|
||||
[macos-progress-bar]: ../images/macos-progress-bar.png
|
||||
[linux-progress-bar]: ../images/linux-progress-bar.png
|
||||
[setprogressbar]: ../api/browser-window.md#winsetprogressbarprogress-options
|
||||
|
||||
@@ -44,7 +44,7 @@ Chromium shared library and Node.js. Vulnerabilities affecting these components
|
||||
may impact the security of your application. By updating Electron to the latest
|
||||
version, you ensure that critical vulnerabilities (such as *nodeIntegration bypasses*)
|
||||
are already patched and cannot be exploited in your application. For more information,
|
||||
see "[Use a current version of Electron](#16-use-a-current-version-of-electron)".
|
||||
see "[Use a current version of Electron](#15-use-a-current-version-of-electron)".
|
||||
|
||||
* **Evaluate your dependencies.** While NPM provides half a million reusable packages,
|
||||
it is your responsibility to choose trusted 3rd-party libraries. If you use outdated
|
||||
@@ -88,19 +88,18 @@ You should at least follow these steps to improve the security of your applicati
|
||||
1. [Only load secure content](#1-only-load-secure-content)
|
||||
2. [Disable the Node.js integration in all renderers that display remote content](#2-do-not-enable-nodejs-integration-for-remote-content)
|
||||
3. [Enable context isolation in all renderers that display remote content](#3-enable-context-isolation-for-remote-content)
|
||||
4. [Enable sandboxing](#4-enable-sandboxing)
|
||||
5. [Use `ses.setPermissionRequestHandler()` in all sessions that load remote content](#5-handle-session-permission-requests-from-remote-content)
|
||||
6. [Do not disable `webSecurity`](#6-do-not-disable-websecurity)
|
||||
7. [Define a `Content-Security-Policy`](#7-define-a-content-security-policy) and use restrictive rules (i.e. `script-src 'self'`)
|
||||
8. [Do not set `allowRunningInsecureContent` to `true`](#8-do-not-set-allowrunninginsecurecontent-to-true)
|
||||
9. [Do not enable experimental features](#9-do-not-enable-experimental-features)
|
||||
10. [Do not use `enableBlinkFeatures`](#10-do-not-use-enableblinkfeatures)
|
||||
11. [`<webview>`: Do not use `allowpopups`](#11-do-not-use-allowpopups)
|
||||
12. [`<webview>`: Verify options and params](#12-verify-webview-options-before-creation)
|
||||
13. [Disable or limit navigation](#13-disable-or-limit-navigation)
|
||||
14. [Disable or limit creation of new windows](#14-disable-or-limit-creation-of-new-windows)
|
||||
15. [Do not use `openExternal` with untrusted content](#15-do-not-use-openexternal-with-untrusted-content)
|
||||
16. [Use a current version of Electron](#16-use-a-current-version-of-electron)
|
||||
4. [Use `ses.setPermissionRequestHandler()` in all sessions that load remote content](#4-handle-session-permission-requests-from-remote-content)
|
||||
5. [Do not disable `webSecurity`](#5-do-not-disable-websecurity)
|
||||
6. [Define a `Content-Security-Policy`](#6-define-a-content-security-policy) and use restrictive rules (i.e. `script-src 'self'`)
|
||||
7. [Do not set `allowRunningInsecureContent` to `true`](#7-do-not-set-allowrunninginsecurecontent-to-true)
|
||||
8. [Do not enable experimental features](#8-do-not-enable-experimental-features)
|
||||
9. [Do not use `enableBlinkFeatures`](#9-do-not-use-enableblinkfeatures)
|
||||
10. [`<webview>`: Do not use `allowpopups`](#10-do-not-use-allowpopups)
|
||||
11. [`<webview>`: Verify options and params](#11-verify-webview-options-before-creation)
|
||||
12. [Disable or limit navigation](#12-disable-or-limit-navigation)
|
||||
13. [Disable or limit creation of new windows](#13-disable-or-limit-creation-of-new-windows)
|
||||
14. [Do not use `openExternal` with untrusted content](#14-do-not-use-openexternal-with-untrusted-content)
|
||||
15. [Use a current version of Electron](#15-use-a-current-version-of-electron)
|
||||
|
||||
To automate the detection of misconfigurations and insecure patterns, it is
|
||||
possible to use
|
||||
@@ -240,26 +239,7 @@ and prevent the use of Node primitives `contextIsolation` **must** also be used.
|
||||
For more information on what `contextIsolation` is and how to enable it please
|
||||
see our dedicated [Context Isolation](context-isolation.md) document.
|
||||
|
||||
## 4) Enable Sandboxing
|
||||
|
||||
[Sandboxing](sandbox.md) is a Chromium feature that uses the operating system to
|
||||
significantly limit what renderer processes have access to. You should enable
|
||||
the sandbox in all renderers. Loading, reading or processing any untrusted
|
||||
content in an unsandboxed process, including the main process, is not advised.
|
||||
|
||||
### How?
|
||||
|
||||
When creating a window, pass the `sandbox: true` option in `webPreferences`:
|
||||
|
||||
```js
|
||||
const win = new BrowserWindow({
|
||||
webPreferences: {
|
||||
sandbox: true
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## 5) Handle Session Permission Requests From Remote Content
|
||||
## 4) Handle Session Permission Requests From Remote Content
|
||||
|
||||
You may have seen permission requests while using Chrome: They pop up whenever
|
||||
the website attempts to use a feature that the user has to manually approve (
|
||||
@@ -297,7 +277,7 @@ session
|
||||
})
|
||||
```
|
||||
|
||||
## 6) Do Not Disable WebSecurity
|
||||
## 5) Do Not Disable WebSecurity
|
||||
|
||||
_Recommendation is Electron's default_
|
||||
|
||||
@@ -338,7 +318,7 @@ const mainWindow = new BrowserWindow()
|
||||
<webview src="page.html"></webview>
|
||||
```
|
||||
|
||||
## 7) Define a Content Security Policy
|
||||
## 6) Define a Content Security Policy
|
||||
|
||||
A Content Security Policy (CSP) is an additional layer of protection against
|
||||
cross-site-scripting attacks and data injection attacks. We recommend that they
|
||||
@@ -394,7 +374,7 @@ on a page directly in the markup using a `<meta>` tag:
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'">
|
||||
```
|
||||
|
||||
## 8) Do Not Set `allowRunningInsecureContent` to `true`
|
||||
## 7) Do Not Set `allowRunningInsecureContent` to `true`
|
||||
|
||||
_Recommendation is Electron's default_
|
||||
|
||||
@@ -427,7 +407,7 @@ const mainWindow = new BrowserWindow({
|
||||
const mainWindow = new BrowserWindow({})
|
||||
```
|
||||
|
||||
## 9) Do Not Enable Experimental Features
|
||||
## 8) Do Not Enable Experimental Features
|
||||
|
||||
_Recommendation is Electron's default_
|
||||
|
||||
@@ -459,7 +439,7 @@ const mainWindow = new BrowserWindow({
|
||||
const mainWindow = new BrowserWindow({})
|
||||
```
|
||||
|
||||
## 10) Do Not Use `enableBlinkFeatures`
|
||||
## 9) Do Not Use `enableBlinkFeatures`
|
||||
|
||||
_Recommendation is Electron's default_
|
||||
|
||||
@@ -491,7 +471,7 @@ const mainWindow = new BrowserWindow({
|
||||
const mainWindow = new BrowserWindow()
|
||||
```
|
||||
|
||||
## 11) Do Not Use `allowpopups`
|
||||
## 10) Do Not Use `allowpopups`
|
||||
|
||||
_Recommendation is Electron's default_
|
||||
|
||||
@@ -518,7 +498,7 @@ you know it needs that feature.
|
||||
<webview src="page.html"></webview>
|
||||
```
|
||||
|
||||
## 12) Verify WebView Options Before Creation
|
||||
## 11) Verify WebView Options Before Creation
|
||||
|
||||
A WebView created in a renderer process that does not have Node.js integration
|
||||
enabled will not be able to enable integration itself. However, a WebView will
|
||||
@@ -565,7 +545,7 @@ app.on('web-contents-created', (event, contents) => {
|
||||
Again, this list merely minimizes the risk, it does not remove it. If your goal
|
||||
is to display a website, a browser will be a more secure option.
|
||||
|
||||
## 13) Disable or limit navigation
|
||||
## 12) Disable or limit navigation
|
||||
|
||||
If your app has no need to navigate or only needs to navigate to known pages,
|
||||
it is a good idea to limit navigation outright to that known scope, disallowing
|
||||
@@ -609,7 +589,7 @@ app.on('web-contents-created', (event, contents) => {
|
||||
})
|
||||
```
|
||||
|
||||
## 14) Disable or limit creation of new windows
|
||||
## 13) Disable or limit creation of new windows
|
||||
|
||||
If you have a known set of windows, it's a good idea to limit the creation of
|
||||
additional windows in your app.
|
||||
@@ -656,7 +636,7 @@ app.on('web-contents-created', (event, contents) => {
|
||||
})
|
||||
```
|
||||
|
||||
## 15) Do not use `openExternal` with untrusted content
|
||||
## 14) Do not use `openExternal` with untrusted content
|
||||
|
||||
Shell's [`openExternal`][open-external] allows opening a given protocol URI with
|
||||
the desktop's native utilities. On macOS, for instance, this function is similar
|
||||
@@ -683,7 +663,7 @@ const { shell } = require('electron')
|
||||
shell.openExternal('https://example.com/index.html')
|
||||
```
|
||||
|
||||
## 16) Use a current version of Electron
|
||||
## 15) Use a current version of Electron
|
||||
|
||||
You should strive for always using the latest available version of Electron.
|
||||
Whenever a new major version is released, you should attempt to update your
|
||||
|
||||
@@ -70,9 +70,9 @@ until the maintainers feel the maintenance burden is too high to continue doing
|
||||
|
||||
### Currently supported versions
|
||||
|
||||
* 14.x.y
|
||||
* 13.x.y
|
||||
* 12.x.y
|
||||
* 11.x.y
|
||||
|
||||
### End-of-life
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ match a public release, instruct `npm` to use the version of Node you have bundl
|
||||
with your custom build.
|
||||
|
||||
```sh
|
||||
npm rebuild --nodedir=/path/to/src/out/Default/gen/node_headers
|
||||
npm rebuild --nodedir=/path/to/electron/vendor/node
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
@@ -125,7 +125,5 @@
|
||||
</message>
|
||||
<message name="IDS_BADGE_UNREAD_NOTIFICATIONS" desc="The accessibility text which will be read by a screen reader when there are notifcatications">
|
||||
{UNREAD_NOTIFICATIONS, plural, =1 {1 Unread Notification} other {# Unread Notifications}}
|
||||
</message>
|
||||
<message name="IDS_HID_CHOOSER_ITEM_WITHOUT_NAME" desc="User option displaying the device IDs for a Human Interface Device (HID) without a device name.">
|
||||
Unknown Device (<ph name="DEVICE_ID">$1<ex>1234:abcd</ex></ph>) </message>
|
||||
</message>
|
||||
</grit-part>
|
||||
|
||||
@@ -42,6 +42,7 @@ auto_filenames = {
|
||||
"docs/api/power-save-blocker.md",
|
||||
"docs/api/process.md",
|
||||
"docs/api/protocol.md",
|
||||
"docs/api/remote.md",
|
||||
"docs/api/screen.md",
|
||||
"docs/api/service-workers.md",
|
||||
"docs/api/session.md",
|
||||
@@ -83,7 +84,6 @@ auto_filenames = {
|
||||
"docs/api/structures/file-filter.md",
|
||||
"docs/api/structures/file-path-with-headers.md",
|
||||
"docs/api/structures/gpu-feature-status.md",
|
||||
"docs/api/structures/hid-device.md",
|
||||
"docs/api/structures/input-event.md",
|
||||
"docs/api/structures/io-counters.md",
|
||||
"docs/api/structures/ipc-main-event.md",
|
||||
@@ -129,26 +129,33 @@ auto_filenames = {
|
||||
"docs/api/structures/upload-data.md",
|
||||
"docs/api/structures/upload-file.md",
|
||||
"docs/api/structures/upload-raw-data.md",
|
||||
"docs/api/structures/user-default-types.md",
|
||||
"docs/api/structures/web-source.md",
|
||||
]
|
||||
|
||||
sandbox_bundle_deps = [
|
||||
"lib/browser/api/module-names.ts",
|
||||
"lib/common/api/clipboard.ts",
|
||||
"lib/common/api/deprecate.ts",
|
||||
"lib/common/api/module-list.ts",
|
||||
"lib/common/api/shell.ts",
|
||||
"lib/common/define-properties.ts",
|
||||
"lib/common/ipc-messages.ts",
|
||||
"lib/common/remote/ipc-messages.ts",
|
||||
"lib/common/type-utils.ts",
|
||||
"lib/common/web-view-events.ts",
|
||||
"lib/common/web-view-methods.ts",
|
||||
"lib/common/webpack-globals-provider.ts",
|
||||
"lib/renderer/api/context-bridge.ts",
|
||||
"lib/renderer/api/crash-reporter.ts",
|
||||
"lib/renderer/api/desktop-capturer.ts",
|
||||
"lib/renderer/api/ipc-renderer.ts",
|
||||
"lib/renderer/api/native-image.ts",
|
||||
"lib/renderer/api/remote.ts",
|
||||
"lib/renderer/api/web-frame.ts",
|
||||
"lib/renderer/inspector.ts",
|
||||
"lib/renderer/ipc-renderer-internal-utils.ts",
|
||||
"lib/renderer/ipc-renderer-internal.ts",
|
||||
"lib/renderer/remote/callbacks-registry.ts",
|
||||
"lib/renderer/security-warnings.ts",
|
||||
"lib/renderer/web-frame-init.ts",
|
||||
"lib/renderer/web-view/guest-view-internal.ts",
|
||||
@@ -169,13 +176,9 @@ auto_filenames = {
|
||||
]
|
||||
|
||||
isolated_bundle_deps = [
|
||||
"lib/common/type-utils.ts",
|
||||
"lib/common/web-view-methods.ts",
|
||||
"lib/isolated_renderer/init.ts",
|
||||
"lib/renderer/web-view/web-view-attributes.ts",
|
||||
"lib/renderer/web-view/web-view-constants.ts",
|
||||
"lib/renderer/web-view/web-view-element.ts",
|
||||
"lib/renderer/web-view/web-view-impl.ts",
|
||||
"package.json",
|
||||
"tsconfig.electron.json",
|
||||
"tsconfig.json",
|
||||
@@ -236,6 +239,9 @@ auto_filenames = {
|
||||
"lib/browser/ipc-main-internal-utils.ts",
|
||||
"lib/browser/ipc-main-internal.ts",
|
||||
"lib/browser/message-port-main.ts",
|
||||
"lib/browser/navigation-controller.ts",
|
||||
"lib/browser/remote/objects-registry.ts",
|
||||
"lib/browser/remote/server.ts",
|
||||
"lib/browser/rpc-server.ts",
|
||||
"lib/common/api/clipboard.ts",
|
||||
"lib/common/api/deprecate.ts",
|
||||
@@ -245,6 +251,7 @@ auto_filenames = {
|
||||
"lib/common/init.ts",
|
||||
"lib/common/ipc-messages.ts",
|
||||
"lib/common/parse-features-string.ts",
|
||||
"lib/common/remote/ipc-messages.ts",
|
||||
"lib/common/reset-search-paths.ts",
|
||||
"lib/common/type-utils.ts",
|
||||
"lib/common/web-view-events.ts",
|
||||
@@ -260,6 +267,7 @@ auto_filenames = {
|
||||
]
|
||||
|
||||
renderer_bundle_deps = [
|
||||
"lib/browser/api/module-names.ts",
|
||||
"lib/common/api/clipboard.ts",
|
||||
"lib/common/api/deprecate.ts",
|
||||
"lib/common/api/module-list.ts",
|
||||
@@ -267,10 +275,12 @@ auto_filenames = {
|
||||
"lib/common/define-properties.ts",
|
||||
"lib/common/init.ts",
|
||||
"lib/common/ipc-messages.ts",
|
||||
"lib/common/remote/ipc-messages.ts",
|
||||
"lib/common/reset-search-paths.ts",
|
||||
"lib/common/type-utils.ts",
|
||||
"lib/common/web-view-events.ts",
|
||||
"lib/common/web-view-methods.ts",
|
||||
"lib/common/webpack-globals-provider.ts",
|
||||
"lib/common/webpack-provider.ts",
|
||||
"lib/renderer/api/context-bridge.ts",
|
||||
"lib/renderer/api/crash-reporter.ts",
|
||||
@@ -279,11 +289,13 @@ auto_filenames = {
|
||||
"lib/renderer/api/ipc-renderer.ts",
|
||||
"lib/renderer/api/module-list.ts",
|
||||
"lib/renderer/api/native-image.ts",
|
||||
"lib/renderer/api/remote.ts",
|
||||
"lib/renderer/api/web-frame.ts",
|
||||
"lib/renderer/init.ts",
|
||||
"lib/renderer/inspector.ts",
|
||||
"lib/renderer/ipc-renderer-internal-utils.ts",
|
||||
"lib/renderer/ipc-renderer-internal.ts",
|
||||
"lib/renderer/remote/callbacks-registry.ts",
|
||||
"lib/renderer/security-warnings.ts",
|
||||
"lib/renderer/web-frame-init.ts",
|
||||
"lib/renderer/web-view/guest-view-internal.ts",
|
||||
@@ -301,6 +313,7 @@ auto_filenames = {
|
||||
]
|
||||
|
||||
worker_bundle_deps = [
|
||||
"lib/browser/api/module-names.ts",
|
||||
"lib/common/api/clipboard.ts",
|
||||
"lib/common/api/deprecate.ts",
|
||||
"lib/common/api/module-list.ts",
|
||||
@@ -308,8 +321,10 @@ auto_filenames = {
|
||||
"lib/common/define-properties.ts",
|
||||
"lib/common/init.ts",
|
||||
"lib/common/ipc-messages.ts",
|
||||
"lib/common/remote/ipc-messages.ts",
|
||||
"lib/common/reset-search-paths.ts",
|
||||
"lib/common/type-utils.ts",
|
||||
"lib/common/webpack-globals-provider.ts",
|
||||
"lib/common/webpack-provider.ts",
|
||||
"lib/renderer/api/context-bridge.ts",
|
||||
"lib/renderer/api/crash-reporter.ts",
|
||||
@@ -318,9 +333,11 @@ auto_filenames = {
|
||||
"lib/renderer/api/ipc-renderer.ts",
|
||||
"lib/renderer/api/module-list.ts",
|
||||
"lib/renderer/api/native-image.ts",
|
||||
"lib/renderer/api/remote.ts",
|
||||
"lib/renderer/api/web-frame.ts",
|
||||
"lib/renderer/ipc-renderer-internal-utils.ts",
|
||||
"lib/renderer/ipc-renderer-internal.ts",
|
||||
"lib/renderer/remote/callbacks-registry.ts",
|
||||
"lib/worker/init.ts",
|
||||
"package.json",
|
||||
"tsconfig.electron.json",
|
||||
|
||||
@@ -385,18 +385,8 @@ filenames = {
|
||||
"shell/browser/file_select_helper.cc",
|
||||
"shell/browser/file_select_helper.h",
|
||||
"shell/browser/file_select_helper_mac.mm",
|
||||
"shell/browser/font/electron_font_access_delegate.cc",
|
||||
"shell/browser/font/electron_font_access_delegate.h",
|
||||
"shell/browser/font_defaults.cc",
|
||||
"shell/browser/font_defaults.h",
|
||||
"shell/browser/hid/electron_hid_delegate.cc",
|
||||
"shell/browser/hid/electron_hid_delegate.h",
|
||||
"shell/browser/hid/hid_chooser_context.cc",
|
||||
"shell/browser/hid/hid_chooser_context.h",
|
||||
"shell/browser/hid/hid_chooser_context_factory.cc",
|
||||
"shell/browser/hid/hid_chooser_context_factory.h",
|
||||
"shell/browser/hid/hid_chooser_controller.cc",
|
||||
"shell/browser/hid/hid_chooser_controller.h",
|
||||
"shell/browser/javascript_environment.cc",
|
||||
"shell/browser/javascript_environment.h",
|
||||
"shell/browser/lib/bluetooth_chooser.cc",
|
||||
@@ -524,7 +514,6 @@ filenames = {
|
||||
"shell/common/api/electron_api_native_image.cc",
|
||||
"shell/common/api/electron_api_native_image.h",
|
||||
"shell/common/api/electron_api_shell.cc",
|
||||
"shell/common/api/electron_api_testing.cc",
|
||||
"shell/common/api/electron_api_v8_util.cc",
|
||||
"shell/common/api/electron_bindings.cc",
|
||||
"shell/common/api/electron_bindings.h",
|
||||
@@ -619,8 +608,6 @@ filenames = {
|
||||
"shell/common/keyboard_util.cc",
|
||||
"shell/common/keyboard_util.h",
|
||||
"shell/common/language_util.h",
|
||||
"shell/common/logging.cc",
|
||||
"shell/common/logging.h",
|
||||
"shell/common/mouse_util.cc",
|
||||
"shell/common/mouse_util.h",
|
||||
"shell/common/node_bindings.cc",
|
||||
|
||||
@@ -13,46 +13,23 @@ libcxx_headers = [
|
||||
"//buildtools/third_party/libc++/trunk/include/__functional_base",
|
||||
"//buildtools/third_party/libc++/trunk/include/__functional_base_03",
|
||||
"//buildtools/third_party/libc++/trunk/include/__hash_table",
|
||||
"//buildtools/third_party/libc++/trunk/include/__iterator/concepts.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__iterator/incrementable_traits.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__iterator/iter_move.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__iterator/iterator_traits.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__iterator/readable_traits.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__libcpp_version",
|
||||
"//buildtools/third_party/libc++/trunk/include/__locale",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/addressof.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/allocation_guard.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/allocator.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/allocator_traits.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/auto_ptr.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/compressed_pair.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/construct_at.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/pointer_safety.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/base.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/pointer_traits.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/raw_storage_iterator.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/shared_ptr.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/temporary_buffer.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/uninitialized_algorithms.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/unique_ptr.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__memory/utilities.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__mutex_base",
|
||||
"//buildtools/third_party/libc++/trunk/include/__node_handle",
|
||||
"//buildtools/third_party/libc++/trunk/include/__nullptr",
|
||||
"//buildtools/third_party/libc++/trunk/include/__ranges/access.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__ranges/concepts.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__ranges/data.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__ranges/empty.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__ranges/enable_borrowed_range.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__ranges/size.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__ranges/view.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__split_buffer",
|
||||
"//buildtools/third_party/libc++/trunk/include/__sso_allocator",
|
||||
"//buildtools/third_party/libc++/trunk/include/__std_stream",
|
||||
"//buildtools/third_party/libc++/trunk/include/__string",
|
||||
"//buildtools/third_party/libc++/trunk/include/__support/android/locale_bionic.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__support/fuchsia/xlocale.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__support/ibm/gettod_zos.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__support/ibm/limits.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__support/ibm/locale_mgmt_aix.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__support/ibm/locale_mgmt_zos.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__support/ibm/nanosleep.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__support/ibm/support.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/__support/ibm/xlocale.h",
|
||||
@@ -72,7 +49,6 @@ libcxx_headers = [
|
||||
"//buildtools/third_party/libc++/trunk/include/__tree",
|
||||
"//buildtools/third_party/libc++/trunk/include/__tuple",
|
||||
"//buildtools/third_party/libc++/trunk/include/__undef_macros",
|
||||
"//buildtools/third_party/libc++/trunk/include/__utility/to_underlying.h",
|
||||
"//buildtools/third_party/libc++/trunk/include/algorithm",
|
||||
"//buildtools/third_party/libc++/trunk/include/any",
|
||||
"//buildtools/third_party/libc++/trunk/include/array",
|
||||
@@ -176,7 +152,6 @@ libcxx_headers = [
|
||||
"//buildtools/third_party/libc++/trunk/include/ostream",
|
||||
"//buildtools/third_party/libc++/trunk/include/queue",
|
||||
"//buildtools/third_party/libc++/trunk/include/random",
|
||||
"//buildtools/third_party/libc++/trunk/include/ranges",
|
||||
"//buildtools/third_party/libc++/trunk/include/ratio",
|
||||
"//buildtools/third_party/libc++/trunk/include/regex",
|
||||
"//buildtools/third_party/libc++/trunk/include/scoped_allocator",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
import { Menu } from 'electron/main';
|
||||
import { deprecate, Menu } from 'electron/main';
|
||||
|
||||
const bindings = process._linkedBinding('electron_browser_app');
|
||||
const commandLine = process._linkedBinding('electron_common_command_line');
|
||||
@@ -66,6 +66,19 @@ Object.defineProperty(app, 'applicationMenu', {
|
||||
// The native implementation is not provided on non-windows platforms
|
||||
app.setAppUserModelId = app.setAppUserModelId || (() => {});
|
||||
|
||||
app._setDefaultAppPaths = (packagePath) => {
|
||||
// Set the user path according to application's name.
|
||||
app.setPath('userData', path.join(app.getPath('appData'), app.name!));
|
||||
app.setPath('userCache', path.join(app.getPath('cache'), app.name!));
|
||||
app.setAppPath(packagePath);
|
||||
|
||||
// Add support for --user-data-dir=
|
||||
if (app.commandLine.hasSwitch('user-data-dir')) {
|
||||
const userDataDir = app.commandLine.getSwitchValue('user-data-dir');
|
||||
if (path.isAbsolute(userDataDir)) app.setPath('userData', userDataDir);
|
||||
}
|
||||
};
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
const setDockMenu = app.dock!.setMenu;
|
||||
app.dock!.setMenu = (menu) => {
|
||||
@@ -119,3 +132,7 @@ for (const name of events) {
|
||||
webContents.emit(name, event, ...args);
|
||||
});
|
||||
}
|
||||
|
||||
// Deprecate allowRendererProcessReuse but only if they set it to false, no need to log if
|
||||
// they are setting it to true
|
||||
deprecate.removeProperty({ __proto__: app } as any, 'allowRendererProcessReuse', [false]);
|
||||
|
||||
@@ -37,11 +37,6 @@ Object.defineProperty(BaseWindow.prototype, 'simpleFullScreen', {
|
||||
set: function (simple) { this.setSimpleFullScreen(simple); }
|
||||
});
|
||||
|
||||
Object.defineProperty(BaseWindow.prototype, 'focusable', {
|
||||
get: function () { return this.isFocusable(); },
|
||||
set: function (focusable) { this.setFocusable(focusable); }
|
||||
});
|
||||
|
||||
Object.defineProperty(BaseWindow.prototype, 'kiosk', {
|
||||
get: function () { return this.isKiosk(); },
|
||||
set: function (kiosk) { this.setKiosk(kiosk); }
|
||||
|
||||
@@ -18,7 +18,7 @@ class CrashReporter {
|
||||
|
||||
if (uploadToServer && !submitURL) throw new Error('submitURL must be specified when uploadToServer is true');
|
||||
|
||||
if (!compress && uploadToServer) {
|
||||
if (!compress) {
|
||||
deprecate.log('Sending uncompressed crash reports is deprecated and will be removed in a future version of Electron. Set { compress: true } to opt-in to the new behavior. Crash reports will be uploaded gzipped, which most crash reporting servers support.');
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,11 @@ import { app, BrowserWindow } from 'electron/main';
|
||||
import type { OpenDialogOptions, OpenDialogReturnValue, MessageBoxOptions, SaveDialogOptions, SaveDialogReturnValue, MessageBoxReturnValue, CertificateTrustDialogOptions } from 'electron/main';
|
||||
const dialogBinding = process._linkedBinding('electron_browser_dialog');
|
||||
|
||||
enum DialogType {
|
||||
OPEN = 'OPEN',
|
||||
SAVE = 'SAVE'
|
||||
}
|
||||
|
||||
enum SaveFileDialogProperties {
|
||||
createDirectory = 1 << 0,
|
||||
showHiddenFiles = 1 << 1,
|
||||
@@ -67,6 +72,16 @@ const setupSaveDialogProperties = (properties: (keyof typeof SaveFileDialogPrope
|
||||
return dialogProperties;
|
||||
};
|
||||
|
||||
const setupDialogProperties = (type: DialogType, properties: string[]): number => {
|
||||
if (type === DialogType.OPEN) {
|
||||
return setupOpenDialogProperties(properties as (keyof typeof OpenFileDialogProperties)[]);
|
||||
} else if (type === DialogType.SAVE) {
|
||||
return setupSaveDialogProperties(properties as (keyof typeof SaveFileDialogProperties)[]);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
const saveDialog = (sync: boolean, window: BrowserWindow | null, options?: SaveDialogOptions) => {
|
||||
checkAppInitialized();
|
||||
|
||||
@@ -100,7 +115,7 @@ const saveDialog = (sync: boolean, window: BrowserWindow | null, options?: SaveD
|
||||
nameFieldLabel,
|
||||
showsTagField,
|
||||
window,
|
||||
properties: setupSaveDialogProperties(properties)
|
||||
properties: setupDialogProperties(DialogType.SAVE, properties)
|
||||
};
|
||||
|
||||
return sync ? dialogBinding.showSaveDialogSync(settings) : dialogBinding.showSaveDialog(settings);
|
||||
@@ -141,7 +156,7 @@ const openDialog = (sync: boolean, window: BrowserWindow | null, options?: OpenD
|
||||
message,
|
||||
securityScopedBookmarks,
|
||||
window,
|
||||
properties: setupOpenDialogProperties(properties)
|
||||
properties: setupDialogProperties(DialogType.OPEN, properties)
|
||||
};
|
||||
|
||||
return (sync) ? dialogBinding.showOpenDialogSync(settings) : dialogBinding.showOpenDialog(settings);
|
||||
|
||||
50
lib/browser/api/module-names.ts
Normal file
50
lib/browser/api/module-names.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
// TODO: Figure out a way to not duplicate this information between here and module-list
|
||||
// It is currently duplicated as module-list "require"s all the browser API file and the
|
||||
// remote module in the renderer process depends on that file. As a result webpack
|
||||
// includes all the browser API files in the renderer process as well and we want to avoid that
|
||||
|
||||
// Browser side modules, please sort alphabetically.
|
||||
export const browserModuleNames = [
|
||||
'app',
|
||||
'autoUpdater',
|
||||
'BaseWindow',
|
||||
'BrowserView',
|
||||
'BrowserWindow',
|
||||
'contentTracing',
|
||||
'crashReporter',
|
||||
'dialog',
|
||||
'globalShortcut',
|
||||
'ipcMain',
|
||||
'inAppPurchase',
|
||||
'Menu',
|
||||
'MenuItem',
|
||||
'nativeImage',
|
||||
'nativeTheme',
|
||||
'net',
|
||||
'netLog',
|
||||
'MessageChannelMain',
|
||||
'Notification',
|
||||
'powerMonitor',
|
||||
'powerSaveBlocker',
|
||||
'protocol',
|
||||
'screen',
|
||||
'session',
|
||||
'ShareMenu',
|
||||
'systemPreferences',
|
||||
'TouchBar',
|
||||
'Tray',
|
||||
'View',
|
||||
'webContents',
|
||||
'WebContentsView',
|
||||
'webFrameMain'
|
||||
];
|
||||
|
||||
if (BUILDFLAG(ENABLE_DESKTOP_CAPTURER)) {
|
||||
browserModuleNames.push('desktopCapturer');
|
||||
}
|
||||
|
||||
if (BUILDFLAG(ENABLE_VIEWS_API)) {
|
||||
browserModuleNames.push(
|
||||
'ImageView'
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { app, ipcMain, session, webFrameMain } from 'electron/main';
|
||||
import { app, ipcMain, session, deprecate, webFrameMain } from 'electron/main';
|
||||
import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main';
|
||||
|
||||
import * as url from 'url';
|
||||
import * as path from 'path';
|
||||
import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager';
|
||||
import { parseFeatures } from '@electron/internal/common/parse-features-string';
|
||||
import { NavigationController } from '@electron/internal/browser/navigation-controller';
|
||||
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
|
||||
import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils';
|
||||
import { MessagePortMain } from '@electron/internal/browser/message-port-main';
|
||||
@@ -407,80 +407,6 @@ WebContents.prototype.loadFile = function (filePath, options = {}) {
|
||||
}));
|
||||
};
|
||||
|
||||
WebContents.prototype.loadURL = function (url, options) {
|
||||
if (!options) {
|
||||
options = {};
|
||||
}
|
||||
|
||||
const p = new Promise<void>((resolve, reject) => {
|
||||
const resolveAndCleanup = () => {
|
||||
removeListeners();
|
||||
resolve();
|
||||
};
|
||||
const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => {
|
||||
const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
|
||||
Object.assign(err, { errno: errorCode, code: errorDescription, url });
|
||||
removeListeners();
|
||||
reject(err);
|
||||
};
|
||||
const finishListener = () => {
|
||||
resolveAndCleanup();
|
||||
};
|
||||
const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
|
||||
if (isMainFrame) {
|
||||
rejectAndCleanup(errorCode, errorDescription, validatedURL);
|
||||
}
|
||||
};
|
||||
|
||||
let navigationStarted = false;
|
||||
const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
|
||||
if (isMainFrame) {
|
||||
if (navigationStarted && !isSameDocument) {
|
||||
// the webcontents has started another unrelated navigation in the
|
||||
// main frame (probably from the app calling `loadURL` again); reject
|
||||
// the promise
|
||||
// We should only consider the request aborted if the "navigation" is
|
||||
// actually navigating and not simply transitioning URL state in the
|
||||
// current context. E.g. pushState and `location.hash` changes are
|
||||
// considered navigation events but are triggered with isSameDocument.
|
||||
// We can ignore these to allow virtual routing on page load as long
|
||||
// as the routing does not leave the document
|
||||
return rejectAndCleanup(-3, 'ERR_ABORTED', url);
|
||||
}
|
||||
navigationStarted = true;
|
||||
}
|
||||
};
|
||||
const stopLoadingListener = () => {
|
||||
// By the time we get here, either 'finish' or 'fail' should have fired
|
||||
// if the navigation occurred. However, in some situations (e.g. when
|
||||
// attempting to load a page with a bad scheme), loading will stop
|
||||
// without emitting finish or fail. In this case, we reject the promise
|
||||
// with a generic failure.
|
||||
// TODO(jeremy): enumerate all the cases in which this can happen. If
|
||||
// the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
|
||||
// would be more appropriate.
|
||||
rejectAndCleanup(-2, 'ERR_FAILED', url);
|
||||
};
|
||||
const removeListeners = () => {
|
||||
this.removeListener('did-finish-load', finishListener);
|
||||
this.removeListener('did-fail-load', failListener);
|
||||
this.removeListener('did-start-navigation', navigationListener);
|
||||
this.removeListener('did-stop-loading', stopLoadingListener);
|
||||
this.removeListener('destroyed', stopLoadingListener);
|
||||
};
|
||||
this.on('did-finish-load', finishListener);
|
||||
this.on('did-fail-load', failListener);
|
||||
this.on('did-start-navigation', navigationListener);
|
||||
this.on('did-stop-loading', stopLoadingListener);
|
||||
this.on('destroyed', stopLoadingListener);
|
||||
});
|
||||
// Add a no-op rejection handler to silence the unhandled rejection error.
|
||||
p.catch(() => {});
|
||||
this._loadURL(url, options);
|
||||
this.emit('load-url', url, options);
|
||||
return p;
|
||||
};
|
||||
|
||||
WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'allow'} | {action: 'deny', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions})) {
|
||||
this._windowOpenHandler = handler;
|
||||
};
|
||||
@@ -549,6 +475,24 @@ const loggingEnabled = () => {
|
||||
|
||||
// Add JavaScript wrappers for WebContents class.
|
||||
WebContents.prototype._init = function () {
|
||||
// The navigation controller.
|
||||
const navigationController = new NavigationController(this);
|
||||
this.loadURL = navigationController.loadURL.bind(navigationController);
|
||||
this.getURL = navigationController.getURL.bind(navigationController);
|
||||
this.stop = navigationController.stop.bind(navigationController);
|
||||
this.reload = navigationController.reload.bind(navigationController);
|
||||
this.reloadIgnoringCache = navigationController.reloadIgnoringCache.bind(navigationController);
|
||||
this.canGoBack = navigationController.canGoBack.bind(navigationController);
|
||||
this.canGoForward = navigationController.canGoForward.bind(navigationController);
|
||||
this.canGoToIndex = navigationController.canGoToIndex.bind(navigationController);
|
||||
this.canGoToOffset = navigationController.canGoToOffset.bind(navigationController);
|
||||
this.clearHistory = navigationController.clearHistory.bind(navigationController);
|
||||
this.goBack = navigationController.goBack.bind(navigationController);
|
||||
this.goForward = navigationController.goForward.bind(navigationController);
|
||||
this.goToIndex = navigationController.goToIndex.bind(navigationController);
|
||||
this.goToOffset = navigationController.goToOffset.bind(navigationController);
|
||||
this.getActiveIndex = navigationController.getActiveIndex.bind(navigationController);
|
||||
this.length = navigationController.length.bind(navigationController);
|
||||
// Read off the ID at construction time, so that it's accessible even after
|
||||
// the underlying C++ WebContents is destroyed.
|
||||
const id = this.id;
|
||||
@@ -559,6 +503,10 @@ WebContents.prototype._init = function () {
|
||||
|
||||
this._windowOpenHandler = null;
|
||||
|
||||
// Every remote callback from renderer process would add a listener to the
|
||||
// render-view-deleted event, so ignore the listeners warning.
|
||||
this.setMaxListeners(0);
|
||||
|
||||
// Dispatch IPC messages to the ipc module.
|
||||
this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
|
||||
addSenderFrameToEvent(event);
|
||||
@@ -593,9 +541,6 @@ WebContents.prototype._init = function () {
|
||||
ipcMainInternal.emit(channel, event, ...args);
|
||||
} else {
|
||||
addReplyToEvent(event);
|
||||
if (this.listenerCount('ipc-message-sync') === 0 && ipcMain.listenerCount(channel) === 0) {
|
||||
console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`);
|
||||
}
|
||||
this.emit('ipc-message-sync', event, channel, ...args);
|
||||
ipcMain.emit(channel, event, ...args);
|
||||
}
|
||||
@@ -669,16 +614,6 @@ WebContents.prototype._init = function () {
|
||||
postBody
|
||||
};
|
||||
windowOpenOverriddenOptions = this._callWindowOpenHandler(event, details);
|
||||
// if attempting to use this API with the deprecated new-window event,
|
||||
// windowOpenOverriddenOptions will always return null. This ensures
|
||||
// short-term backwards compatibility until new-window is removed.
|
||||
const parsedFeatures = parseFeatures(rawFeatures);
|
||||
const overriddenFeatures: BrowserWindowConstructorOptions = {
|
||||
...parsedFeatures.options,
|
||||
webPreferences: parsedFeatures.webPreferences
|
||||
};
|
||||
windowOpenOverriddenOptions = windowOpenOverriddenOptions || overriddenFeatures;
|
||||
|
||||
if (!event.defaultPrevented) {
|
||||
const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
|
||||
// Allow setting of backgroundColor as a webPreference even though
|
||||
@@ -723,6 +658,11 @@ WebContents.prototype._init = function () {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const prefs = this.getWebPreferences() || {};
|
||||
if (prefs.webviewTag && prefs.contextIsolation) {
|
||||
deprecate.log('Security Warning: A WebContents was just created with both webviewTag and contextIsolation enabled. This combination is fundamentally less secure and effectively bypasses the protections of contextIsolation. We strongly recommend you move away from webviews to OOPIF or BrowserView in order for your app to be more secure');
|
||||
}
|
||||
}
|
||||
|
||||
this.on('login', (event, ...args) => {
|
||||
@@ -738,14 +678,6 @@ WebContents.prototype._init = function () {
|
||||
}
|
||||
});
|
||||
|
||||
this.on('select-bluetooth-device', (event, devices, callback) => {
|
||||
if (this.listenerCount('select-bluetooth-device') === 0) {
|
||||
// Cancel it if there are no handlers
|
||||
event.preventDefault();
|
||||
callback('');
|
||||
}
|
||||
});
|
||||
|
||||
const event = process._linkedBinding('electron_browser_event').createEmpty();
|
||||
app.emit('web-contents-created', event, this);
|
||||
|
||||
|
||||
@@ -7,11 +7,7 @@ WebFrameMain.prototype.send = function (channel, ...args) {
|
||||
throw new Error('Missing required channel argument');
|
||||
}
|
||||
|
||||
try {
|
||||
return this._send(false /* internal */, channel, args);
|
||||
} catch (e) {
|
||||
console.error('Error sending from webFrameMain: ', e);
|
||||
}
|
||||
return this._send(false /* internal */, channel, args);
|
||||
};
|
||||
|
||||
WebFrameMain.prototype._sendInternal = function (channel, ...args) {
|
||||
@@ -19,11 +15,7 @@ WebFrameMain.prototype._sendInternal = function (channel, ...args) {
|
||||
throw new Error('Missing required channel argument');
|
||||
}
|
||||
|
||||
try {
|
||||
return this._send(true /* internal */, channel, args);
|
||||
} catch (e) {
|
||||
console.error('Error sending from webFrameMain: ', e);
|
||||
}
|
||||
return this._send(true /* internal */, channel, args);
|
||||
};
|
||||
|
||||
WebFrameMain.prototype.postMessage = function (...args) {
|
||||
|
||||
@@ -13,7 +13,7 @@ function isValid (options: Electron.SourcesOptions) {
|
||||
return Array.isArray(types);
|
||||
}
|
||||
|
||||
export const getSourcesImpl = (sender: Electron.WebContents | null, args: Electron.SourcesOptions) => {
|
||||
export const getSourcesImpl = (event: Electron.IpcMainEvent | null, args: Electron.SourcesOptions) => {
|
||||
if (!isValid(args)) throw new Error('Invalid options');
|
||||
|
||||
const captureWindow = args.types.includes('window');
|
||||
@@ -48,8 +48,8 @@ export const getSourcesImpl = (sender: Electron.WebContents | null, args: Electr
|
||||
}
|
||||
// Remove from currentlyRunning once we resolve or reject
|
||||
currentlyRunning = currentlyRunning.filter(running => running.options !== options);
|
||||
if (sender) {
|
||||
sender.removeListener('destroyed', stopRunning);
|
||||
if (event) {
|
||||
event.sender.removeListener('destroyed', stopRunning);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -68,8 +68,8 @@ export const getSourcesImpl = (sender: Electron.WebContents | null, args: Electr
|
||||
// If the WebContents is destroyed before receiving result, just remove the
|
||||
// reference to emit and the capturer itself so that it never dispatches
|
||||
// back to the renderer
|
||||
if (sender) {
|
||||
sender.once('destroyed', stopRunning);
|
||||
if (event) {
|
||||
event.sender.once('destroyed', stopRunning);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ const isChromeDevTools = function (pageURL: string) {
|
||||
};
|
||||
|
||||
const assertChromeDevTools = function (contents: Electron.WebContents, api: string) {
|
||||
const pageURL = contents.getURL();
|
||||
const pageURL = contents._getURL();
|
||||
if (!isChromeDevTools(pageURL)) {
|
||||
console.error(`Blocked ${pageURL} from calling ${api}`);
|
||||
throw new Error(`Blocked ${api}`);
|
||||
|
||||
@@ -34,12 +34,12 @@ const createGuest = function (embedder: Electron.WebContents, params: Record<str
|
||||
const guest = (webContents as typeof ElectronInternal.WebContents).create({
|
||||
type: 'webview',
|
||||
partition: params.partition,
|
||||
embedder
|
||||
embedder: embedder
|
||||
});
|
||||
const guestInstanceId = guest.id;
|
||||
guestInstances.set(guestInstanceId, {
|
||||
guest,
|
||||
embedder
|
||||
guest: guest,
|
||||
embedder: embedder
|
||||
});
|
||||
|
||||
// Clear the guest from map when it is destroyed.
|
||||
@@ -165,9 +165,10 @@ const attachGuest = function (event: Electron.IpcMainInvokeEvent,
|
||||
: null;
|
||||
|
||||
const webPreferences: Electron.WebPreferences = {
|
||||
guestInstanceId,
|
||||
guestInstanceId: guestInstanceId,
|
||||
nodeIntegration: params.nodeintegration != null ? params.nodeintegration : false,
|
||||
nodeIntegrationInSubFrames: params.nodeintegrationinsubframes != null ? params.nodeintegrationinsubframes : false,
|
||||
enableRemoteModule: params.enableremotemodule,
|
||||
plugins: params.plugins,
|
||||
zoomFactor: embedder.zoomFactor,
|
||||
disablePopups: !params.allowpopups,
|
||||
@@ -187,6 +188,7 @@ const attachGuest = function (event: Electron.IpcMainInvokeEvent,
|
||||
['javascript', false],
|
||||
['nativeWindowOpen', true],
|
||||
['nodeIntegration', false],
|
||||
['enableRemoteModule', false],
|
||||
['sandbox', true],
|
||||
['nodeIntegrationInSubFrames', false],
|
||||
['enableWebSQL', false]
|
||||
@@ -216,7 +218,7 @@ const attachGuest = function (event: Electron.IpcMainInvokeEvent,
|
||||
|
||||
watchEmbedder(embedder);
|
||||
|
||||
webViewManager.addGuest(guestInstanceId, embedder, guest, webPreferences);
|
||||
webViewManager.addGuest(guestInstanceId, elementInstanceId, embedder, guest, webPreferences);
|
||||
guest.attachToIframe(embedder, embedderFrameId);
|
||||
};
|
||||
|
||||
@@ -319,8 +321,13 @@ handleMessageSync(IPC_MESSAGES.GUEST_VIEW_MANAGER_DETACH_GUEST, function (event,
|
||||
});
|
||||
|
||||
// this message is sent by the actual <webview>
|
||||
ipcMainInternal.on(IPC_MESSAGES.GUEST_VIEW_MANAGER_FOCUS_CHANGE, function (event: ElectronInternal.IpcMainInternalEvent, focus: boolean) {
|
||||
event.sender.emit('-focus-change', {}, focus);
|
||||
ipcMainInternal.on(IPC_MESSAGES.GUEST_VIEW_MANAGER_FOCUS_CHANGE, function (event: ElectronInternal.IpcMainInternalEvent, focus: boolean, guestInstanceId: number) {
|
||||
const guest = getGuest(guestInstanceId);
|
||||
if (guest === event.sender) {
|
||||
event.sender.emit('focus-change', {}, focus, guestInstanceId);
|
||||
} else {
|
||||
console.error(`focus-change for guestInstanceId: ${guestInstanceId}`);
|
||||
}
|
||||
});
|
||||
|
||||
handleMessage(IPC_MESSAGES.GUEST_VIEW_MANAGER_CALL, function (event, guestInstanceId: number, method: string, args: any[]) {
|
||||
@@ -367,12 +374,18 @@ handleMessage(IPC_MESSAGES.GUEST_VIEW_MANAGER_CAPTURE_PAGE, async function (even
|
||||
|
||||
// Returns WebContents from its guest id hosted in given webContents.
|
||||
const getGuestForWebContents = function (guestInstanceId: number, contents: Electron.WebContents) {
|
||||
const guestInstance = guestInstances.get(guestInstanceId);
|
||||
if (!guestInstance) {
|
||||
const guest = getGuest(guestInstanceId);
|
||||
if (!guest) {
|
||||
throw new Error(`Invalid guestInstanceId: ${guestInstanceId}`);
|
||||
}
|
||||
if (guestInstance.guest.hostWebContents !== contents) {
|
||||
if (guest.hostWebContents !== contents) {
|
||||
throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`);
|
||||
}
|
||||
return guestInstance.guest;
|
||||
return guest;
|
||||
};
|
||||
|
||||
// Returns WebContents from its guest id.
|
||||
const getGuest = function (guestInstanceId: number) {
|
||||
const guestInstance = guestInstances.get(guestInstanceId);
|
||||
if (guestInstance != null) return guestInstance.guest;
|
||||
};
|
||||
|
||||
@@ -42,7 +42,7 @@ export function openGuestWindow ({ event, embedder, guest, referrer, disposition
|
||||
windowOpenArgs: WindowOpenArgs,
|
||||
}): BrowserWindow | undefined {
|
||||
const { url, frameName, features } = windowOpenArgs;
|
||||
const { options: browserWindowOptions } = makeBrowserWindowOptions({
|
||||
const { options: browserWindowOptions, additionalFeatures } = makeBrowserWindowOptions({
|
||||
embedder,
|
||||
features,
|
||||
overrideOptions: overrideBrowserWindowOptions
|
||||
@@ -54,6 +54,7 @@ export function openGuestWindow ({ event, embedder, guest, referrer, disposition
|
||||
guest,
|
||||
browserWindowOptions,
|
||||
windowOpenArgs,
|
||||
additionalFeatures,
|
||||
disposition,
|
||||
postData,
|
||||
referrer
|
||||
@@ -65,13 +66,8 @@ export function openGuestWindow ({ event, embedder, guest, referrer, disposition
|
||||
// https://html.spec.whatwg.org/multipage/window-object.html#apis-for-creating-and-navigating-browsing-contexts-by-name
|
||||
const existingWindow = getGuestWindowByFrameName(frameName);
|
||||
if (existingWindow) {
|
||||
if (existingWindow.isDestroyed() || existingWindow.webContents.isDestroyed()) {
|
||||
// FIXME(t57ser): The webContents is destroyed for some reason, unregister the frame name
|
||||
unregisterFrameName(frameName);
|
||||
} else {
|
||||
existingWindow.loadURL(url);
|
||||
return existingWindow;
|
||||
}
|
||||
existingWindow.loadURL(url);
|
||||
return existingWindow;
|
||||
}
|
||||
|
||||
const window = new BrowserWindow({
|
||||
@@ -97,7 +93,7 @@ export function openGuestWindow ({ event, embedder, guest, referrer, disposition
|
||||
|
||||
handleWindowLifecycleEvents({ embedder, frameName, guest: window });
|
||||
|
||||
embedder.emit('did-create-window', window, { url, frameName, options: browserWindowOptions, disposition, referrer, postData });
|
||||
embedder.emit('did-create-window', window, { url, frameName, options: browserWindowOptions, disposition, additionalFeatures, referrer, postData });
|
||||
|
||||
return window;
|
||||
}
|
||||
@@ -138,12 +134,13 @@ const handleWindowLifecycleEvents = function ({ embedder, guest, frameName }: {
|
||||
* Deprecated in favor of `webContents.setWindowOpenHandler` and
|
||||
* `did-create-window` in 11.0.0. Will be removed in 12.0.0.
|
||||
*/
|
||||
function emitDeprecatedNewWindowEvent ({ event, embedder, guest, windowOpenArgs, browserWindowOptions, disposition, referrer, postData }: {
|
||||
function emitDeprecatedNewWindowEvent ({ event, embedder, guest, windowOpenArgs, browserWindowOptions, additionalFeatures, disposition, referrer, postData }: {
|
||||
event: { sender: WebContents, defaultPrevented: boolean, newGuest?: BrowserWindow },
|
||||
embedder: WebContents,
|
||||
guest?: WebContents,
|
||||
windowOpenArgs: WindowOpenArgs,
|
||||
browserWindowOptions: BrowserWindowConstructorOptions,
|
||||
additionalFeatures: string[]
|
||||
disposition: string,
|
||||
referrer: Referrer,
|
||||
postData?: PostData,
|
||||
@@ -165,7 +162,7 @@ function emitDeprecatedNewWindowEvent ({ event, embedder, guest, windowOpenArgs,
|
||||
...browserWindowOptions,
|
||||
webContents: guest
|
||||
},
|
||||
[], // additionalFeatures
|
||||
additionalFeatures,
|
||||
referrer,
|
||||
postBody
|
||||
);
|
||||
@@ -197,43 +194,49 @@ const securityWebPreferences: { [key: string]: boolean } = {
|
||||
javascript: false,
|
||||
nativeWindowOpen: true,
|
||||
nodeIntegration: false,
|
||||
enableRemoteModule: false,
|
||||
sandbox: true,
|
||||
webviewTag: false,
|
||||
nodeIntegrationInSubFrames: false,
|
||||
enableWebSQL: false
|
||||
};
|
||||
|
||||
function makeBrowserWindowOptions ({ embedder, features, overrideOptions }: {
|
||||
function makeBrowserWindowOptions ({ embedder, features, overrideOptions, useDeprecatedBehaviorForBareValues = true, useDeprecatedBehaviorForOptionInheritance = true }: {
|
||||
embedder: WebContents,
|
||||
features: string,
|
||||
overrideOptions?: BrowserWindowConstructorOptions,
|
||||
useDeprecatedBehaviorForBareValues?: boolean
|
||||
useDeprecatedBehaviorForOptionInheritance?: boolean
|
||||
}) {
|
||||
const { options: parsedOptions, webPreferences: parsedWebPreferences } = parseFeatures(features);
|
||||
const { options: parsedOptions, webPreferences: parsedWebPreferences, additionalFeatures } = parseFeatures(features, useDeprecatedBehaviorForBareValues);
|
||||
|
||||
const deprecatedInheritedOptions = getDeprecatedInheritedOptions(embedder);
|
||||
|
||||
return {
|
||||
additionalFeatures,
|
||||
options: {
|
||||
...(useDeprecatedBehaviorForOptionInheritance && deprecatedInheritedOptions),
|
||||
show: true,
|
||||
width: 800,
|
||||
height: 600,
|
||||
...parsedOptions,
|
||||
...overrideOptions,
|
||||
webPreferences: makeWebPreferences({
|
||||
embedder,
|
||||
insecureParsedWebPreferences: parsedWebPreferences,
|
||||
secureOverrideWebPreferences: overrideOptions && overrideOptions.webPreferences
|
||||
})
|
||||
webPreferences: makeWebPreferences({ embedder, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences: overrideOptions && overrideOptions.webPreferences, useDeprecatedBehaviorForOptionInheritance: true })
|
||||
} as Electron.BrowserViewConstructorOptions
|
||||
};
|
||||
}
|
||||
|
||||
export function makeWebPreferences ({ embedder, secureOverrideWebPreferences = {}, insecureParsedWebPreferences: parsedWebPreferences = {} }: {
|
||||
export function makeWebPreferences ({ embedder, secureOverrideWebPreferences = {}, insecureParsedWebPreferences: parsedWebPreferences = {}, useDeprecatedBehaviorForOptionInheritance = true }: {
|
||||
embedder: WebContents,
|
||||
insecureParsedWebPreferences?: ReturnType<typeof parseFeatures>['webPreferences'],
|
||||
// Note that override preferences are considered elevated, and should only be
|
||||
// sourced from the main process, as they override security defaults. If you
|
||||
// have unvetted prefs, use parsedWebPreferences.
|
||||
secureOverrideWebPreferences?: BrowserWindowConstructorOptions['webPreferences'],
|
||||
useDeprecatedBehaviorForBareValues?: boolean
|
||||
useDeprecatedBehaviorForOptionInheritance?: boolean
|
||||
}) {
|
||||
const deprecatedInheritedOptions = getDeprecatedInheritedOptions(embedder);
|
||||
const parentWebPreferences = embedder.getLastWebPreferences();
|
||||
const securityWebPreferencesFromParent = (Object.keys(securityWebPreferences).reduce((map, key) => {
|
||||
if (securityWebPreferences[key] === parentWebPreferences[key as keyof Electron.WebPreferences]) {
|
||||
@@ -244,6 +247,7 @@ export function makeWebPreferences ({ embedder, secureOverrideWebPreferences = {
|
||||
const openerId = parentWebPreferences.nativeWindowOpen ? null : embedder.id;
|
||||
|
||||
return {
|
||||
...(useDeprecatedBehaviorForOptionInheritance && deprecatedInheritedOptions ? deprecatedInheritedOptions.webPreferences : null),
|
||||
...parsedWebPreferences,
|
||||
// Note that order is key here, we want to disallow the renderer's
|
||||
// ability to change important security options but allow main (via
|
||||
@@ -256,6 +260,25 @@ export function makeWebPreferences ({ embedder, secureOverrideWebPreferences = {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Current Electron behavior is to inherit all options from the parent window.
|
||||
* In practical use, this is kind of annoying because consumers have to know
|
||||
* about the parent window's preferences in order to unset them and makes child
|
||||
* windows even more of an anomaly. In 11.0.0 we will remove this behavior and
|
||||
* only critical security preferences will be inherited by default.
|
||||
*/
|
||||
function getDeprecatedInheritedOptions (embedder: WebContents) {
|
||||
if (!embedder.browserWindowOptions) {
|
||||
// If it's a webview, return just the webPreferences.
|
||||
return {
|
||||
webPreferences: embedder.getLastWebPreferences()
|
||||
};
|
||||
}
|
||||
|
||||
const { type, show, ...inheritableOptions } = embedder.browserWindowOptions;
|
||||
return inheritableOptions;
|
||||
}
|
||||
|
||||
function formatPostDataHeaders (postData: PostData) {
|
||||
if (!postData) return;
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ handleMessage(
|
||||
|
||||
if (!windowMethods.has(method)) {
|
||||
console.error(
|
||||
`Blocked ${event.senderFrame.url} from calling method: ${method}`
|
||||
`Blocked ${event.sender.getURL()} from calling method: ${method}`
|
||||
);
|
||||
throw new Error(`Invalid method: ${method}`);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ import { EventEmitter } from 'events';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
import type * as defaultMenuModule from '@electron/internal/browser/default-menu';
|
||||
|
||||
const Module = require('module');
|
||||
|
||||
// We modified the original process.argv to let node.js load the init.js,
|
||||
@@ -129,11 +127,15 @@ if (packageJson.v8Flags != null) {
|
||||
require('v8').setFlagsFromString(packageJson.v8Flags);
|
||||
}
|
||||
|
||||
app.setAppPath(packagePath);
|
||||
app._setDefaultAppPaths(packagePath);
|
||||
|
||||
// Load the chrome devtools support.
|
||||
require('@electron/internal/browser/devtools');
|
||||
|
||||
if (BUILDFLAG(ENABLE_REMOTE_MODULE)) {
|
||||
require('@electron/internal/browser/remote/server');
|
||||
}
|
||||
|
||||
// Load protocol module to ensure it is populated on app ready
|
||||
require('@electron/internal/browser/api/protocol');
|
||||
|
||||
@@ -174,7 +176,7 @@ app.on('window-all-closed', () => {
|
||||
}
|
||||
});
|
||||
|
||||
const { setDefaultApplicationMenu } = require('@electron/internal/browser/default-menu') as typeof defaultMenuModule;
|
||||
const { setDefaultApplicationMenu } = require('@electron/internal/browser/default-menu');
|
||||
|
||||
// Create default menu.
|
||||
//
|
||||
|
||||
228
lib/browser/navigation-controller.ts
Normal file
228
lib/browser/navigation-controller.ts
Normal file
@@ -0,0 +1,228 @@
|
||||
import type { WebContents, LoadURLOptions } from 'electron/main';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
// JavaScript implementation of Chromium's NavigationController.
|
||||
// Instead of relying on Chromium for history control, we completely do history
|
||||
// control on user land, and only rely on WebContents.loadURL for navigation.
|
||||
// This helps us avoid Chromium's various optimizations so we can ensure renderer
|
||||
// process is restarted every time.
|
||||
export class NavigationController extends EventEmitter {
|
||||
currentIndex: number = -1;
|
||||
inPageIndex: number = -1;
|
||||
pendingIndex: number = -1;
|
||||
history: string[] = [];
|
||||
|
||||
constructor (private webContents: WebContents) {
|
||||
super();
|
||||
this.clearHistory();
|
||||
|
||||
// webContents may have already navigated to a page.
|
||||
if (this.webContents._getURL()) {
|
||||
this.currentIndex++;
|
||||
this.history.push(this.webContents._getURL());
|
||||
}
|
||||
this.webContents.on('navigation-entry-committed' as any, (event: Electron.Event, url: string, inPage: boolean, replaceEntry: boolean) => {
|
||||
if (this.inPageIndex > -1 && !inPage) {
|
||||
// Navigated to a new page, clear in-page mark.
|
||||
this.inPageIndex = -1;
|
||||
} else if (this.inPageIndex === -1 && inPage && !replaceEntry) {
|
||||
// Started in-page navigations.
|
||||
this.inPageIndex = this.currentIndex;
|
||||
}
|
||||
if (this.pendingIndex >= 0) {
|
||||
// Go to index.
|
||||
this.currentIndex = this.pendingIndex;
|
||||
this.pendingIndex = -1;
|
||||
this.history[this.currentIndex] = url;
|
||||
} else if (replaceEntry) {
|
||||
// Non-user initialized navigation.
|
||||
this.history[this.currentIndex] = url;
|
||||
} else {
|
||||
// Normal navigation. Clear history.
|
||||
this.history = this.history.slice(0, this.currentIndex + 1);
|
||||
this.currentIndex++;
|
||||
this.history.push(url);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
loadURL (url: string, options?: LoadURLOptions): Promise<void> {
|
||||
if (options == null) {
|
||||
options = {};
|
||||
}
|
||||
const p = new Promise<void>((resolve, reject) => {
|
||||
const resolveAndCleanup = () => {
|
||||
removeListeners();
|
||||
resolve();
|
||||
};
|
||||
const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => {
|
||||
const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
|
||||
Object.assign(err, { errno: errorCode, code: errorDescription, url });
|
||||
removeListeners();
|
||||
reject(err);
|
||||
};
|
||||
const finishListener = () => {
|
||||
resolveAndCleanup();
|
||||
};
|
||||
const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
|
||||
if (isMainFrame) {
|
||||
rejectAndCleanup(errorCode, errorDescription, validatedURL);
|
||||
}
|
||||
};
|
||||
|
||||
let navigationStarted = false;
|
||||
const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
|
||||
if (isMainFrame) {
|
||||
if (navigationStarted && !isSameDocument) {
|
||||
// the webcontents has started another unrelated navigation in the
|
||||
// main frame (probably from the app calling `loadURL` again); reject
|
||||
// the promise
|
||||
// We should only consider the request aborted if the "navigation" is
|
||||
// actually navigating and not simply transitioning URL state in the
|
||||
// current context. E.g. pushState and `location.hash` changes are
|
||||
// considered navigation events but are triggered with isSameDocument.
|
||||
// We can ignore these to allow virtual routing on page load as long
|
||||
// as the routing does not leave the document
|
||||
return rejectAndCleanup(-3, 'ERR_ABORTED', url);
|
||||
}
|
||||
navigationStarted = true;
|
||||
}
|
||||
};
|
||||
const stopLoadingListener = () => {
|
||||
// By the time we get here, either 'finish' or 'fail' should have fired
|
||||
// if the navigation occurred. However, in some situations (e.g. when
|
||||
// attempting to load a page with a bad scheme), loading will stop
|
||||
// without emitting finish or fail. In this case, we reject the promise
|
||||
// with a generic failure.
|
||||
// TODO(jeremy): enumerate all the cases in which this can happen. If
|
||||
// the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
|
||||
// would be more appropriate.
|
||||
rejectAndCleanup(-2, 'ERR_FAILED', url);
|
||||
};
|
||||
const removeListeners = () => {
|
||||
this.webContents.removeListener('did-finish-load', finishListener);
|
||||
this.webContents.removeListener('did-fail-load', failListener);
|
||||
this.webContents.removeListener('did-start-navigation', navigationListener);
|
||||
this.webContents.removeListener('did-stop-loading', stopLoadingListener);
|
||||
this.webContents.removeListener('destroyed', stopLoadingListener);
|
||||
};
|
||||
this.webContents.on('did-finish-load', finishListener);
|
||||
this.webContents.on('did-fail-load', failListener);
|
||||
this.webContents.on('did-start-navigation', navigationListener);
|
||||
this.webContents.on('did-stop-loading', stopLoadingListener);
|
||||
this.webContents.on('destroyed', stopLoadingListener);
|
||||
});
|
||||
// Add a no-op rejection handler to silence the unhandled rejection error.
|
||||
p.catch(() => {});
|
||||
this.pendingIndex = -1;
|
||||
this.webContents._loadURL(url, options);
|
||||
this.webContents.emit('load-url', url, options);
|
||||
return p;
|
||||
}
|
||||
|
||||
getURL () {
|
||||
if (this.currentIndex === -1) {
|
||||
return '';
|
||||
} else {
|
||||
return this.history[this.currentIndex];
|
||||
}
|
||||
}
|
||||
|
||||
stop () {
|
||||
this.pendingIndex = -1;
|
||||
return this.webContents._stop();
|
||||
}
|
||||
|
||||
reload () {
|
||||
this.pendingIndex = this.currentIndex;
|
||||
return this.webContents._loadURL(this.getURL(), {});
|
||||
}
|
||||
|
||||
reloadIgnoringCache () {
|
||||
this.pendingIndex = this.currentIndex;
|
||||
return this.webContents._loadURL(this.getURL(), {
|
||||
extraHeaders: 'pragma: no-cache\n',
|
||||
reloadIgnoringCache: true
|
||||
});
|
||||
}
|
||||
|
||||
canGoBack () {
|
||||
return this.getActiveIndex() > 0;
|
||||
}
|
||||
|
||||
canGoForward () {
|
||||
return this.getActiveIndex() < this.history.length - 1;
|
||||
}
|
||||
|
||||
canGoToIndex (index: number) {
|
||||
return index >= 0 && index < this.history.length;
|
||||
}
|
||||
|
||||
canGoToOffset (offset: number) {
|
||||
return this.canGoToIndex(this.currentIndex + offset);
|
||||
}
|
||||
|
||||
clearHistory () {
|
||||
this.history = [];
|
||||
this.currentIndex = -1;
|
||||
this.pendingIndex = -1;
|
||||
this.inPageIndex = -1;
|
||||
}
|
||||
|
||||
goBack () {
|
||||
if (!this.canGoBack()) {
|
||||
return;
|
||||
}
|
||||
this.pendingIndex = this.getActiveIndex() - 1;
|
||||
if (this.inPageIndex > -1 && this.pendingIndex >= this.inPageIndex) {
|
||||
return this.webContents._goBack();
|
||||
} else {
|
||||
return this.webContents._loadURL(this.history[this.pendingIndex], {});
|
||||
}
|
||||
}
|
||||
|
||||
goForward () {
|
||||
if (!this.canGoForward()) {
|
||||
return;
|
||||
}
|
||||
this.pendingIndex = this.getActiveIndex() + 1;
|
||||
if (this.inPageIndex > -1 && this.pendingIndex >= this.inPageIndex) {
|
||||
return this.webContents._goForward();
|
||||
} else {
|
||||
return this.webContents._loadURL(this.history[this.pendingIndex], {});
|
||||
}
|
||||
}
|
||||
|
||||
goToIndex (index: number) {
|
||||
if (!this.canGoToIndex(index)) {
|
||||
return;
|
||||
}
|
||||
this.pendingIndex = index;
|
||||
return this.webContents._loadURL(this.history[this.pendingIndex], {});
|
||||
}
|
||||
|
||||
goToOffset (offset: number) {
|
||||
if (!this.canGoToOffset(offset)) {
|
||||
return;
|
||||
}
|
||||
const pendingIndex = this.currentIndex + offset;
|
||||
if (this.inPageIndex > -1 && pendingIndex >= this.inPageIndex) {
|
||||
this.pendingIndex = pendingIndex;
|
||||
return this.webContents._goToOffset(offset);
|
||||
} else {
|
||||
return this.goToIndex(pendingIndex);
|
||||
}
|
||||
}
|
||||
|
||||
getActiveIndex () {
|
||||
if (this.pendingIndex === -1) {
|
||||
return this.currentIndex;
|
||||
} else {
|
||||
return this.pendingIndex;
|
||||
}
|
||||
}
|
||||
|
||||
length () {
|
||||
return this.history.length;
|
||||
}
|
||||
}
|
||||
128
lib/browser/remote/objects-registry.ts
Normal file
128
lib/browser/remote/objects-registry.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { WebContents } from 'electron/main';
|
||||
|
||||
const getOwnerKey = (webContents: WebContents, contextId: string) => {
|
||||
return `${webContents.id}-${contextId}`;
|
||||
};
|
||||
|
||||
class ObjectsRegistry {
|
||||
private nextId: number = 0
|
||||
|
||||
// Stores all objects by ref-counting.
|
||||
// (id) => {object, count}
|
||||
private storage: Record<number, { count: number, object: any }> = {}
|
||||
|
||||
// Stores the IDs + refCounts of objects referenced by WebContents.
|
||||
// (ownerKey) => { id: refCount }
|
||||
private owners: Record<string, Map<number, number>> = {}
|
||||
|
||||
private electronIds = new WeakMap<Object, number>();
|
||||
|
||||
// Register a new object and return its assigned ID. If the object is already
|
||||
// registered then the already assigned ID would be returned.
|
||||
add (webContents: WebContents, contextId: string, obj: any) {
|
||||
// Get or assign an ID to the object.
|
||||
const id = this.saveToStorage(obj);
|
||||
|
||||
// Add object to the set of referenced objects.
|
||||
const ownerKey = getOwnerKey(webContents, contextId);
|
||||
let owner = this.owners[ownerKey];
|
||||
if (!owner) {
|
||||
owner = this.owners[ownerKey] = new Map();
|
||||
this.registerDeleteListener(webContents, contextId);
|
||||
}
|
||||
if (!owner.has(id)) {
|
||||
owner.set(id, 0);
|
||||
// Increase reference count if not referenced before.
|
||||
this.storage[id].count++;
|
||||
}
|
||||
|
||||
owner.set(id, owner.get(id)! + 1);
|
||||
return id;
|
||||
}
|
||||
|
||||
// Get an object according to its ID.
|
||||
get (id: number) {
|
||||
const pointer = this.storage[id];
|
||||
if (pointer != null) return pointer.object;
|
||||
}
|
||||
|
||||
// Dereference an object according to its ID.
|
||||
// Note that an object may be double-freed (cleared when page is reloaded, and
|
||||
// then garbage collected in old page).
|
||||
remove (webContents: WebContents, contextId: string, id: number) {
|
||||
const ownerKey = getOwnerKey(webContents, contextId);
|
||||
const owner = this.owners[ownerKey];
|
||||
if (owner && owner.has(id)) {
|
||||
const newRefCount = owner.get(id)! - 1;
|
||||
|
||||
// Only completely remove if the number of references GCed in the
|
||||
// renderer is the same as the number of references we sent them
|
||||
if (newRefCount <= 0) {
|
||||
// Remove the reference in owner.
|
||||
owner.delete(id);
|
||||
// Dereference from the storage.
|
||||
this.dereference(id);
|
||||
} else {
|
||||
owner.set(id, newRefCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clear all references to objects refrenced by the WebContents.
|
||||
clear (webContents: WebContents, contextId: string) {
|
||||
const ownerKey = getOwnerKey(webContents, contextId);
|
||||
const owner = this.owners[ownerKey];
|
||||
if (!owner) return;
|
||||
|
||||
for (const id of owner.keys()) this.dereference(id);
|
||||
|
||||
delete this.owners[ownerKey];
|
||||
}
|
||||
|
||||
// Private: Saves the object into storage and assigns an ID for it.
|
||||
saveToStorage (object: any) {
|
||||
let id = this.electronIds.get(object);
|
||||
if (!id) {
|
||||
id = ++this.nextId;
|
||||
this.storage[id] = {
|
||||
count: 0,
|
||||
object: object
|
||||
};
|
||||
this.electronIds.set(object, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
// Private: Dereference the object from store.
|
||||
dereference (id: number) {
|
||||
const pointer = this.storage[id];
|
||||
if (pointer == null) {
|
||||
return;
|
||||
}
|
||||
pointer.count -= 1;
|
||||
if (pointer.count === 0) {
|
||||
this.electronIds.delete(pointer.object);
|
||||
delete this.storage[id];
|
||||
}
|
||||
}
|
||||
|
||||
// Private: Clear the storage when renderer process is destroyed.
|
||||
registerDeleteListener (webContents: WebContents, contextId: string) {
|
||||
// contextId => ${processHostId}-${contextCount}
|
||||
const processHostId = contextId.split('-')[0];
|
||||
const listener = (_: any, deletedProcessHostId: string) => {
|
||||
if (deletedProcessHostId &&
|
||||
deletedProcessHostId.toString() === processHostId) {
|
||||
webContents.removeListener('render-view-deleted' as any, listener);
|
||||
this.clear(webContents, contextId);
|
||||
}
|
||||
};
|
||||
// Note that the "render-view-deleted" event may not be emitted on time when
|
||||
// the renderer process get destroyed because of navigation, we rely on the
|
||||
// renderer process to send "ELECTRON_BROWSER_CONTEXT_RELEASE" message to
|
||||
// guard this situation.
|
||||
webContents.on('render-view-deleted' as any, listener);
|
||||
}
|
||||
}
|
||||
|
||||
export default new ObjectsRegistry();
|
||||
519
lib/browser/remote/server.ts
Normal file
519
lib/browser/remote/server.ts
Normal file
@@ -0,0 +1,519 @@
|
||||
import * as electron from 'electron/main';
|
||||
import { EventEmitter } from 'events';
|
||||
import objectsRegistry from '@electron/internal/browser/remote/objects-registry';
|
||||
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
|
||||
import { isPromise, isSerializableObject, deserialize, serialize } from '@electron/internal/common/type-utils';
|
||||
import type { MetaTypeFromRenderer, ObjectMember, MetaType, ObjProtoDescriptor } from '@electron/internal/common/remote/types';
|
||||
import { IPC_MESSAGES } from '@electron/internal/common/remote/ipc-messages';
|
||||
|
||||
const v8Util = process._linkedBinding('electron_common_v8_util');
|
||||
const eventBinding = process._linkedBinding('electron_browser_event');
|
||||
const features = process._linkedBinding('electron_common_features');
|
||||
|
||||
if (!features.isRemoteModuleEnabled()) {
|
||||
throw new Error('remote module is disabled');
|
||||
}
|
||||
|
||||
// The internal properties of Function.
|
||||
const FUNCTION_PROPERTIES = [
|
||||
'length', 'name', 'arguments', 'caller', 'prototype'
|
||||
];
|
||||
|
||||
type RendererFunctionId = [string, number] // [contextId, funcId]
|
||||
type FinalizerInfo = { id: RendererFunctionId, webContents: electron.WebContents, frameId: [number, number] };
|
||||
type CallIntoRenderer = (...args: any[]) => void
|
||||
|
||||
// The remote functions in renderer processes.
|
||||
const rendererFunctionCache = new Map<string, WeakRef<CallIntoRenderer>>();
|
||||
// eslint-disable-next-line no-undef
|
||||
const finalizationRegistry = new FinalizationRegistry((fi: FinalizerInfo) => {
|
||||
const mapKey = fi.id[0] + '~' + fi.id[1];
|
||||
const ref = rendererFunctionCache.get(mapKey);
|
||||
if (ref !== undefined && ref.deref() === undefined) {
|
||||
rendererFunctionCache.delete(mapKey);
|
||||
if (!fi.webContents.isDestroyed()) {
|
||||
try {
|
||||
fi.webContents._sendToFrameInternal(fi.frameId, IPC_MESSAGES.RENDERER_RELEASE_CALLBACK, fi.id[0], fi.id[1]);
|
||||
} catch (error) {
|
||||
console.warn(`_sendToFrameInternal() failed: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function getCachedRendererFunction (id: RendererFunctionId): CallIntoRenderer | undefined {
|
||||
const mapKey = id[0] + '~' + id[1];
|
||||
const ref = rendererFunctionCache.get(mapKey);
|
||||
if (ref !== undefined) {
|
||||
const deref = ref.deref();
|
||||
if (deref !== undefined) return deref;
|
||||
}
|
||||
}
|
||||
function setCachedRendererFunction (id: RendererFunctionId, wc: electron.WebContents, frameId: [number, number], value: CallIntoRenderer) {
|
||||
// eslint-disable-next-line no-undef
|
||||
const wr = new WeakRef<CallIntoRenderer>(value);
|
||||
const mapKey = id[0] + '~' + id[1];
|
||||
rendererFunctionCache.set(mapKey, wr);
|
||||
finalizationRegistry.register(value, {
|
||||
id,
|
||||
webContents: wc,
|
||||
frameId
|
||||
} as FinalizerInfo);
|
||||
return value;
|
||||
}
|
||||
|
||||
const locationInfo = new WeakMap<Object, string>();
|
||||
|
||||
// Return the description of object's members:
|
||||
const getObjectMembers = function (object: any): ObjectMember[] {
|
||||
let names = Object.getOwnPropertyNames(object);
|
||||
// For Function, we should not override following properties even though they
|
||||
// are "own" properties.
|
||||
if (typeof object === 'function') {
|
||||
names = names.filter((name) => {
|
||||
return !FUNCTION_PROPERTIES.includes(name);
|
||||
});
|
||||
}
|
||||
// Map properties to descriptors.
|
||||
return names.map((name) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(object, name)!;
|
||||
let type: ObjectMember['type'];
|
||||
let writable = false;
|
||||
if (descriptor.get === undefined && typeof object[name] === 'function') {
|
||||
type = 'method';
|
||||
} else {
|
||||
if (descriptor.set || descriptor.writable) writable = true;
|
||||
type = 'get';
|
||||
}
|
||||
return { name, enumerable: descriptor.enumerable, writable, type };
|
||||
});
|
||||
};
|
||||
|
||||
// Return the description of object's prototype.
|
||||
const getObjectPrototype = function (object: any): ObjProtoDescriptor {
|
||||
const proto = Object.getPrototypeOf(object);
|
||||
if (proto === null || proto === Object.prototype) return null;
|
||||
return {
|
||||
members: getObjectMembers(proto),
|
||||
proto: getObjectPrototype(proto)
|
||||
};
|
||||
};
|
||||
|
||||
// Convert a real value into meta data.
|
||||
const valueToMeta = function (sender: electron.WebContents, contextId: string, value: any, optimizeSimpleObject = false): MetaType {
|
||||
// Determine the type of value.
|
||||
let type: MetaType['type'];
|
||||
|
||||
switch (typeof value) {
|
||||
case 'object':
|
||||
// Recognize certain types of objects.
|
||||
if (value instanceof Buffer) {
|
||||
type = 'buffer';
|
||||
} else if (value && value.constructor && value.constructor.name === 'NativeImage') {
|
||||
type = 'nativeimage';
|
||||
} else if (Array.isArray(value)) {
|
||||
type = 'array';
|
||||
} else if (value instanceof Error) {
|
||||
type = 'error';
|
||||
} else if (isSerializableObject(value)) {
|
||||
type = 'value';
|
||||
} else if (isPromise(value)) {
|
||||
type = 'promise';
|
||||
} else if (Object.prototype.hasOwnProperty.call(value, 'callee') && value.length != null) {
|
||||
// Treat the arguments object as array.
|
||||
type = 'array';
|
||||
} else if (optimizeSimpleObject && v8Util.getHiddenValue(value, 'simple')) {
|
||||
// Treat simple objects as value.
|
||||
type = 'value';
|
||||
} else {
|
||||
type = 'object';
|
||||
}
|
||||
break;
|
||||
case 'function':
|
||||
type = 'function';
|
||||
break;
|
||||
default:
|
||||
type = 'value';
|
||||
break;
|
||||
}
|
||||
|
||||
// Fill the meta object according to value's type.
|
||||
if (type === 'array') {
|
||||
return {
|
||||
type,
|
||||
members: value.map((el: any) => valueToMeta(sender, contextId, el, optimizeSimpleObject))
|
||||
};
|
||||
} else if (type === 'nativeimage') {
|
||||
return { type, value: serialize(value) };
|
||||
} else if (type === 'object' || type === 'function') {
|
||||
return {
|
||||
type,
|
||||
name: value.constructor ? value.constructor.name : '',
|
||||
// Reference the original value if it's an object, because when it's
|
||||
// passed to renderer we would assume the renderer keeps a reference of
|
||||
// it.
|
||||
id: objectsRegistry.add(sender, contextId, value),
|
||||
members: getObjectMembers(value),
|
||||
proto: getObjectPrototype(value)
|
||||
};
|
||||
} else if (type === 'buffer') {
|
||||
return { type, value };
|
||||
} else if (type === 'promise') {
|
||||
// Add default handler to prevent unhandled rejections in main process
|
||||
// Instead they should appear in the renderer process
|
||||
value.then(function () {}, function () {});
|
||||
|
||||
return {
|
||||
type,
|
||||
then: valueToMeta(sender, contextId, function (onFulfilled: Function, onRejected: Function) {
|
||||
value.then(onFulfilled, onRejected);
|
||||
})
|
||||
};
|
||||
} else if (type === 'error') {
|
||||
return {
|
||||
type,
|
||||
value,
|
||||
members: Object.keys(value).map(name => ({
|
||||
name,
|
||||
value: valueToMeta(sender, contextId, value[name])
|
||||
}))
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
type: 'value',
|
||||
value
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const throwRPCError = function (message: string) {
|
||||
const error = new Error(message) as Error & {code: string, errno: number};
|
||||
error.code = 'EBADRPC';
|
||||
error.errno = -72;
|
||||
throw error;
|
||||
};
|
||||
|
||||
const removeRemoteListenersAndLogWarning = (sender: any, callIntoRenderer: (...args: any[]) => void) => {
|
||||
const location = locationInfo.get(callIntoRenderer);
|
||||
let message = 'Attempting to call a function in a renderer window that has been closed or released.' +
|
||||
`\nFunction provided here: ${location}`;
|
||||
|
||||
if (sender instanceof EventEmitter) {
|
||||
const remoteEvents = sender.eventNames().filter((eventName) => {
|
||||
return sender.listeners(eventName).includes(callIntoRenderer);
|
||||
});
|
||||
|
||||
if (remoteEvents.length > 0) {
|
||||
message += `\nRemote event names: ${remoteEvents.join(', ')}`;
|
||||
remoteEvents.forEach((eventName) => {
|
||||
sender.removeListener(eventName, callIntoRenderer);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.warn(message);
|
||||
};
|
||||
|
||||
const fakeConstructor = (constructor: Function, name: string) =>
|
||||
new Proxy(Object, {
|
||||
get (target, prop, receiver) {
|
||||
if (prop === 'name') {
|
||||
return name;
|
||||
} else {
|
||||
return Reflect.get(target, prop, receiver);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Convert array of meta data from renderer into array of real values.
|
||||
const unwrapArgs = function (sender: electron.WebContents, frameId: [number, number], contextId: string, args: any[]) {
|
||||
const metaToValue = function (meta: MetaTypeFromRenderer): any {
|
||||
switch (meta.type) {
|
||||
case 'nativeimage':
|
||||
return deserialize(meta.value);
|
||||
case 'value':
|
||||
return meta.value;
|
||||
case 'remote-object':
|
||||
return objectsRegistry.get(meta.id);
|
||||
case 'array':
|
||||
return unwrapArgs(sender, frameId, contextId, meta.value);
|
||||
case 'buffer':
|
||||
return Buffer.from(meta.value.buffer, meta.value.byteOffset, meta.value.byteLength);
|
||||
case 'promise':
|
||||
return Promise.resolve({
|
||||
then: metaToValue(meta.then)
|
||||
});
|
||||
case 'object': {
|
||||
const ret: any = meta.name !== 'Object' ? Object.create({
|
||||
constructor: fakeConstructor(Object, meta.name)
|
||||
}) : {};
|
||||
|
||||
for (const { name, value } of meta.members) {
|
||||
ret[name] = metaToValue(value);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
case 'function-with-return-value': {
|
||||
const returnValue = metaToValue(meta.value);
|
||||
return function () {
|
||||
return returnValue;
|
||||
};
|
||||
}
|
||||
case 'function': {
|
||||
// Merge contextId and meta.id, since meta.id can be the same in
|
||||
// different webContents.
|
||||
const objectId: [string, number] = [contextId, meta.id];
|
||||
|
||||
// Cache the callbacks in renderer.
|
||||
const cachedFunction = getCachedRendererFunction(objectId);
|
||||
if (cachedFunction !== undefined) { return cachedFunction; }
|
||||
|
||||
const callIntoRenderer = function (this: any, ...args: any[]) {
|
||||
let succeed = false;
|
||||
if (!sender.isDestroyed()) {
|
||||
try {
|
||||
succeed = sender._sendToFrameInternal(frameId, IPC_MESSAGES.RENDERER_CALLBACK, contextId, meta.id, valueToMeta(sender, contextId, args));
|
||||
} catch (error) {
|
||||
console.warn(`_sendToFrameInternal() failed: ${error}`);
|
||||
}
|
||||
}
|
||||
if (!succeed) {
|
||||
removeRemoteListenersAndLogWarning(this, callIntoRenderer);
|
||||
}
|
||||
};
|
||||
locationInfo.set(callIntoRenderer, meta.location);
|
||||
Object.defineProperty(callIntoRenderer, 'length', { value: meta.length });
|
||||
|
||||
setCachedRendererFunction(objectId, sender, frameId, callIntoRenderer);
|
||||
return callIntoRenderer;
|
||||
}
|
||||
default:
|
||||
throw new TypeError(`Unknown type: ${(meta as any).type}`);
|
||||
}
|
||||
};
|
||||
return args.map(metaToValue);
|
||||
};
|
||||
|
||||
const isRemoteModuleEnabledImpl = function (contents: electron.WebContents) {
|
||||
const webPreferences = contents.getLastWebPreferences() || {};
|
||||
return webPreferences.enableRemoteModule != null ? !!webPreferences.enableRemoteModule : false;
|
||||
};
|
||||
|
||||
const isRemoteModuleEnabledCache = new WeakMap();
|
||||
|
||||
export const isRemoteModuleEnabled = function (contents: electron.WebContents) {
|
||||
if (!isRemoteModuleEnabledCache.has(contents)) {
|
||||
isRemoteModuleEnabledCache.set(contents, isRemoteModuleEnabledImpl(contents));
|
||||
}
|
||||
|
||||
return isRemoteModuleEnabledCache.get(contents);
|
||||
};
|
||||
|
||||
const handleRemoteCommand = function (channel: string, handler: (event: ElectronInternal.IpcMainInternalEvent, contextId: string, ...args: any[]) => void) {
|
||||
ipcMainInternal.on(channel, (event, contextId: string, ...args: any[]) => {
|
||||
let returnValue;
|
||||
if (!isRemoteModuleEnabled(event.sender)) {
|
||||
event.returnValue = null;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
returnValue = handler(event, contextId, ...args);
|
||||
} catch (error) {
|
||||
returnValue = {
|
||||
type: 'exception',
|
||||
value: valueToMeta(event.sender, contextId, error)
|
||||
};
|
||||
}
|
||||
|
||||
if (returnValue !== undefined) {
|
||||
event.returnValue = returnValue;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const emitCustomEvent = function (contents: electron.WebContents, eventName: string, ...args: any[]) {
|
||||
const event = eventBinding.createWithSender(contents);
|
||||
|
||||
electron.app.emit(eventName, event, contents, ...args);
|
||||
contents.emit(eventName, event, ...args);
|
||||
|
||||
return event;
|
||||
};
|
||||
|
||||
const logStack = function (contents: electron.WebContents, code: string, stack: string | undefined) {
|
||||
if (stack) {
|
||||
console.warn(`WebContents (${contents.id}): ${code}`, stack);
|
||||
}
|
||||
};
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_WRONG_CONTEXT_ERROR, function (event, contextId, passedContextId, id) {
|
||||
const objectId: [string, number] = [passedContextId, id];
|
||||
const cachedFunction = getCachedRendererFunction(objectId);
|
||||
if (cachedFunction === undefined) {
|
||||
// Do nothing if the error has already been reported before.
|
||||
return;
|
||||
}
|
||||
removeRemoteListenersAndLogWarning(event.sender, cachedFunction);
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_REQUIRE, function (event, contextId, moduleName, stack) {
|
||||
logStack(event.sender, `remote.require('${moduleName}')`, stack);
|
||||
const customEvent = emitCustomEvent(event.sender, 'remote-require', moduleName);
|
||||
|
||||
if (customEvent.returnValue === undefined) {
|
||||
if (customEvent.defaultPrevented) {
|
||||
throw new Error(`Blocked remote.require('${moduleName}')`);
|
||||
} else {
|
||||
customEvent.returnValue = process.mainModule.require(moduleName);
|
||||
}
|
||||
}
|
||||
|
||||
return valueToMeta(event.sender, contextId, customEvent.returnValue);
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_GET_BUILTIN, function (event, contextId, moduleName, stack) {
|
||||
logStack(event.sender, `remote.getBuiltin('${moduleName}')`, stack);
|
||||
const customEvent = emitCustomEvent(event.sender, 'remote-get-builtin', moduleName);
|
||||
|
||||
if (customEvent.returnValue === undefined) {
|
||||
if (customEvent.defaultPrevented) {
|
||||
throw new Error(`Blocked remote.getBuiltin('${moduleName}')`);
|
||||
} else {
|
||||
customEvent.returnValue = (electron as any)[moduleName];
|
||||
}
|
||||
}
|
||||
|
||||
return valueToMeta(event.sender, contextId, customEvent.returnValue);
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_GET_GLOBAL, function (event, contextId, globalName, stack) {
|
||||
logStack(event.sender, `remote.getGlobal('${globalName}')`, stack);
|
||||
const customEvent = emitCustomEvent(event.sender, 'remote-get-global', globalName);
|
||||
|
||||
if (customEvent.returnValue === undefined) {
|
||||
if (customEvent.defaultPrevented) {
|
||||
throw new Error(`Blocked remote.getGlobal('${globalName}')`);
|
||||
} else {
|
||||
customEvent.returnValue = (global as any)[globalName];
|
||||
}
|
||||
}
|
||||
|
||||
return valueToMeta(event.sender, contextId, customEvent.returnValue);
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_GET_CURRENT_WINDOW, function (event, contextId, stack) {
|
||||
logStack(event.sender, 'remote.getCurrentWindow()', stack);
|
||||
const customEvent = emitCustomEvent(event.sender, 'remote-get-current-window');
|
||||
|
||||
if (customEvent.returnValue === undefined) {
|
||||
if (customEvent.defaultPrevented) {
|
||||
throw new Error('Blocked remote.getCurrentWindow()');
|
||||
} else {
|
||||
customEvent.returnValue = event.sender.getOwnerBrowserWindow();
|
||||
}
|
||||
}
|
||||
|
||||
return valueToMeta(event.sender, contextId, customEvent.returnValue);
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_GET_CURRENT_WEB_CONTENTS, function (event, contextId, stack) {
|
||||
logStack(event.sender, 'remote.getCurrentWebContents()', stack);
|
||||
const customEvent = emitCustomEvent(event.sender, 'remote-get-current-web-contents');
|
||||
|
||||
if (customEvent.returnValue === undefined) {
|
||||
if (customEvent.defaultPrevented) {
|
||||
throw new Error('Blocked remote.getCurrentWebContents()');
|
||||
} else {
|
||||
customEvent.returnValue = event.sender;
|
||||
}
|
||||
}
|
||||
|
||||
return valueToMeta(event.sender, contextId, customEvent.returnValue);
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_CONSTRUCTOR, function (event, contextId, id, args) {
|
||||
args = unwrapArgs(event.sender, [event.processId, event.frameId], contextId, args);
|
||||
const constructor = objectsRegistry.get(id);
|
||||
|
||||
if (constructor == null) {
|
||||
throwRPCError(`Cannot call constructor on missing remote object ${id}`);
|
||||
}
|
||||
|
||||
return valueToMeta(event.sender, contextId, new constructor(...args));
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_FUNCTION_CALL, function (event, contextId, id, args) {
|
||||
args = unwrapArgs(event.sender, [event.processId, event.frameId], contextId, args);
|
||||
const func = objectsRegistry.get(id);
|
||||
|
||||
if (func == null) {
|
||||
throwRPCError(`Cannot call function on missing remote object ${id}`);
|
||||
}
|
||||
|
||||
try {
|
||||
return valueToMeta(event.sender, contextId, func(...args), true);
|
||||
} catch (error) {
|
||||
const err = new Error(`Could not call remote function '${func.name || 'anonymous'}'. Check that the function signature is correct. Underlying error: ${error.message}\nUnderlying stack: ${error.stack}\n`);
|
||||
(err as any).cause = error;
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_MEMBER_CONSTRUCTOR, function (event, contextId, id, method, args) {
|
||||
args = unwrapArgs(event.sender, [event.processId, event.frameId], contextId, args);
|
||||
const object = objectsRegistry.get(id);
|
||||
|
||||
if (object == null) {
|
||||
throwRPCError(`Cannot call constructor '${method}' on missing remote object ${id}`);
|
||||
}
|
||||
|
||||
return valueToMeta(event.sender, contextId, new object[method](...args));
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_MEMBER_CALL, function (event, contextId, id, method, args) {
|
||||
args = unwrapArgs(event.sender, [event.processId, event.frameId], contextId, args);
|
||||
const object = objectsRegistry.get(id);
|
||||
|
||||
if (object == null) {
|
||||
throwRPCError(`Cannot call method '${method}' on missing remote object ${id}`);
|
||||
}
|
||||
|
||||
try {
|
||||
return valueToMeta(event.sender, contextId, object[method](...args), true);
|
||||
} catch (error) {
|
||||
const err = new Error(`Could not call remote method '${method}'. Check that the method signature is correct. Underlying error: ${error.message}\nUnderlying stack: ${error.stack}\n`);
|
||||
(err as any).cause = error;
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_MEMBER_SET, function (event, contextId, id, name, args) {
|
||||
args = unwrapArgs(event.sender, [event.processId, event.frameId], contextId, args);
|
||||
const obj = objectsRegistry.get(id);
|
||||
|
||||
if (obj == null) {
|
||||
throwRPCError(`Cannot set property '${name}' on missing remote object ${id}`);
|
||||
}
|
||||
|
||||
obj[name] = args[0];
|
||||
return null;
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_MEMBER_GET, function (event, contextId, id, name) {
|
||||
const obj = objectsRegistry.get(id);
|
||||
|
||||
if (obj == null) {
|
||||
throwRPCError(`Cannot get property '${name}' on missing remote object ${id}`);
|
||||
}
|
||||
|
||||
return valueToMeta(event.sender, contextId, obj[name]);
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_DEREFERENCE, function (event, contextId, id) {
|
||||
objectsRegistry.remove(event.sender, contextId, id);
|
||||
});
|
||||
|
||||
handleRemoteCommand(IPC_MESSAGES.BROWSER_CONTEXT_RELEASE, (event, contextId) => {
|
||||
objectsRegistry.clear(event.sender, contextId);
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user