|
@@ -0,0 +1,59 @@
|
|
|
+# `electron`获取权限
|
|
|
+> ! windows 平台
|
|
|
+> electron 在尝试用管理员权限执行某个命令
|
|
|
+> 在获取权限时出现部分情况下无法正确获取权限的问题
|
|
|
+
|
|
|
+## 解决方法`elevate`
|
|
|
+在`electron`自身打包出来的`resource`文件夹里有个`elevate.exe`用它执行命令即可
|
|
|
+解决方案来源`vs-code`源码
|
|
|
+## 解决代码1
|
|
|
+```typescript
|
|
|
+ async _spawn(exe: string, args: Array<string>): Promise<any> {
|
|
|
+ return new Promise((resolve, reject) => {
|
|
|
+ try {
|
|
|
+ const elevate = path.join(process.resourcesPath, "elevate.exe");
|
|
|
+
|
|
|
+ const p = spawn(elevate, [exe].concat(args), {
|
|
|
+ detached: true,
|
|
|
+ stdio: "ignore"
|
|
|
+ });
|
|
|
+ p.on("error", (err) => {
|
|
|
+ reject(err.message);
|
|
|
+ });
|
|
|
+
|
|
|
+ p.unref();
|
|
|
+
|
|
|
+ if (p.pid !== undefined) {
|
|
|
+ this.logService.info(`pid = ${p.pid}`);
|
|
|
+ resolve(true);
|
|
|
+ }
|
|
|
+ } catch (err) {
|
|
|
+ reject(err);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+```
|
|
|
+
|
|
|
+## 解决代码2
|
|
|
+```typescript
|
|
|
+ async run(command: string): Promise<void> {
|
|
|
+ const sudoPrompt = await import("sudo-prompt");
|
|
|
+ return new Promise((resolve, reject) => {
|
|
|
+ try {
|
|
|
+ const promptOptions = {
|
|
|
+ name: "xx"
|
|
|
+ };
|
|
|
+ const elevate = path.join(process.resourcesPath, "elevate.exe");
|
|
|
+ sudoPrompt.exec(`"${elevate}" ${command}`, promptOptions, (error) => {
|
|
|
+ if (error) {
|
|
|
+ reject(error);
|
|
|
+ } else {
|
|
|
+ resolve();
|
|
|
+ }
|
|
|
+ });
|
|
|
+ } catch (err) {
|
|
|
+ reject(err);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+```
|