Browse Source

Merge pull request #10 from qa2080639/master

远程调用网页函数
Wallace Gao 4 years ago
parent
commit
9a7365616c

+ 17 - 8
app/controller/v1/example.js

@@ -1,6 +1,6 @@
 'use strict';
 
-const BaseController = require('../base'); 
+const BaseController = require('../base');
 const os = require('os');
 const fs = require('fs');
 const path = require('path');
@@ -20,13 +20,13 @@ class ExampleController extends BaseController {
         break;
       case 'picture' :
         dir = os.userInfo().homedir + '/Pictures';
-        break;    
+        break;
       case 'doc' :
         dir = os.userInfo().homedir + '/Documents';
-        break;      
+        break;
       case 'music' :
         dir = os.userInfo().homedir + '/Music';
-        break;    
+        break;
     }
 
     await service.example.openLocalDir(dir);
@@ -34,6 +34,15 @@ class ExampleController extends BaseController {
     self.sendSuccess(data);
   }
 
+  async executeJS() {
+    const self = this;
+    const { ctx, service } = this;
+    const body = ctx.request.body;
+    const str = body.str;
+    let data = await service.example.executeJS(str);
+    self.sendSuccess(data);
+  }
+
   async uploadFile() {
     const self = this;
     const { ctx, service } = this;
@@ -42,24 +51,24 @@ class ExampleController extends BaseController {
     //   this.app.logger.info('file:', file);
 
     //   try {
-    //     let tmpFile = fs.readFileSync(file.filepath) 
+    //     let tmpFile = fs.readFileSync(file.filepath)
     //     fs.writeFileSync(path.join(tmpDir, file.filename), tmpFile)
     //   } finally {
     //     await fs.unlink(file.filepath, function(){});
     //   }
-    //   const fileStream = fs.createReadStream(path.join(tmpDir, file.filename)) 
+    //   const fileStream = fs.createReadStream(path.join(tmpDir, file.filename))
     //   const uploadRes = await service.example.uploadFileToSMMS(fileStream);
     // }
     const file = ctx.request.files[0];
     //this.app.logger.info('file:', file);
 
     try {
-      let tmpFile = fs.readFileSync(file.filepath) 
+      let tmpFile = fs.readFileSync(file.filepath)
       fs.writeFileSync(path.join(tmpDir, file.filename), tmpFile)
     } finally {
       await fs.unlink(file.filepath, function(){});
     }
-    const fileStream = fs.createReadStream(path.join(tmpDir, file.filename)) 
+    const fileStream = fs.createReadStream(path.join(tmpDir, file.filename))
     const uploadRes = await service.example.uploadFileToSMMS(fileStream);
 
     self.sendData(uploadRes);

+ 2 - 0
app/router/example.js

@@ -7,6 +7,8 @@ module.exports = app => {
   const { router, controller } = app;
   // open local dir
   router.post('/api/v1/example/openLocalDir', controller.v1.example.openLocalDir);
+  // executeJS
+  router.post('/api/v1/example/executeJS', controller.v1.example.executeJS);
   // upload file
   router.post('/api/v1/example/uploadFile', controller.v1.example.uploadFile);
   // get ws url

+ 6 - 0
app/service/example.js

@@ -11,6 +11,12 @@ class ExampleService extends BaseService {
     return true;
   }
 
+  async executeJS(str) {
+    const self = this;
+    let result = await self.ipcCall('example.executeJS', str);
+    return result;
+  }
+
   async uploadFileToSMMS(tmpFile) {
     const res = {
       code: 1000,

+ 18 - 8
electron/api.js

@@ -61,17 +61,27 @@ exports.setup = async function () {
     socket.on('ipc', (message, callback) => {
       ELog.info('[ api ] [setup] socket id:' + socket.id + ' message cmd: ' + message.cmd);
       const data = apis[message.cmd](...message.params);
-      const result = {
-        err: null,
-        data: data,
-      };
-      callback(result);
+      if (data && typeof data.then === 'function') { // 判断是否是异步
+        data.then((data) => {
+          const result = {
+            err: null,
+            data: data,
+          };
+          callback(result)
+        });
+      } else {
+        const result = {
+          err: null,
+          data: data,
+        };
+        callback(result);
+      }
     });
   });
 
   server.listen(port, listen, function() {
     ELog.info('[ api ] [setup] server is listening on', `${listen}:${port}`);
-  });  
+  });
 };
 
 function setApi() {
@@ -88,7 +98,7 @@ function setApi() {
       });
     }
   });
-};
+}
 
 /**
  * get api method name
@@ -99,4 +109,4 @@ function setApi() {
 function getApiName (jsname, method) {
   return jsname + '.' + method;
   //return jsname + method.charAt(0).toUpperCase() + method.slice(1);
-};
+}

+ 14 - 6
electron/apis/example.js

@@ -1,11 +1,14 @@
 'use strict';
 
 const path = require('path');
-const { app, shell } = require('electron');
+const {
+  app,
+  webContents,
+  shell
+} = require('electron');
 
 exports.getPath = function () {
   const dir = app.getAppPath();
-
   return dir;
 }
 
@@ -15,14 +18,19 @@ exports.openDir = function (dir = '') {
   }
   dir = getElectronPath(dir);
   shell.openItem(dir);
-
   return true;
 }
 
-function getElectronPath (filepath) {
+exports.executeJS = function (str) {
+  let jscode = `(()=>{alert('${str}');return 'fromJs:${str}';})()`;
+  console.log(jscode);
+  return webContents.fromId(1).executeJavaScript(jscode);
+}
+
+function getElectronPath(filepath) {
   //filepath = path.resolve(filepath);
-  filepath=filepath.replace("resources",""); 
-  filepath=filepath.replace("app.asar",""); 
+  filepath = filepath.replace("resources", "");
+  filepath = filepath.replace("app.asar", "");
   filepath = path.normalize(filepath);
   return filepath;
 };

+ 12 - 0
frontend/src/api/main.js

@@ -5,6 +5,7 @@ const mainApi = {
   outApi: '/api/v1/outApi',
   openDir: '/api/v1/example/openLocalDir',
   uploadFile: '/api/v1/example/uploadFile',
+  executeJS: '/api/v1/example/executeJS',
   autoLaunchEnable: '/api/v1/setting/autoLaunchEnable',
   autoLaunchDisable: '/api/v1/setting/autoLaunchDisable',
   autoLaunchIsEnabled: '/api/v1/setting/autoLaunchIsEnabled'
@@ -52,4 +53,15 @@ export function uploadFile (parameter) {
     method: 'post',
     data: parameter
   })
+}
+
+/**
+ * executeJS
+ */
+export function executeJS (parameter) {
+  return request({
+    url: mainApi.executeJS,
+    method: 'post',
+    data: parameter
+  })
 }

+ 36 - 11
frontend/src/views/example/Ipc.vue

@@ -1,23 +1,39 @@
 <template>
   <div>
-    <h3 :style="{ marginBottom: '16px' }">
-      demo3 渲染进程与主进程IPC通信
-    </h3>
-    <a-list bordered>
-      <!-- <a-button @click="helloHandle">打招呼</a-button> -->
-      <a-input-search v-model="content" @search="helloHandle">
-        <a-button slot="enterButton">
-          send
-        </a-button>
-      </a-input-search>
-    </a-list>
+    <div>
+      <h3 :style="{ marginBottom: '16px' }">
+        demo3 渲染进程与主进程IPC通信
+      </h3>
+      <a-list bordered>
+        <!-- <a-button @click="helloHandle">打招呼</a-button> -->
+        <a-input-search v-model="content" @search="helloHandle">
+          <a-button slot="enterButton">
+            send
+          </a-button>
+        </a-input-search>
+      </a-list>
+    </div>
+    <div style="margin-top: 20px;">
+      <h3 :style="{ marginBottom: '16px' }">
+        demo4 远程API执行网页函数
+      </h3>
+      <a-list bordered>
+        <a-input-search v-model="content2" @search="executeJSHandle">
+          <a-button slot="enterButton">
+            send
+          </a-button>
+        </a-input-search>
+      </a-list>
+    </div>
   </div>
 </template>
 <script>
+import { executeJS } from '@/api/main'
 export default {
   data() {
     return {
       content: 'hello',
+      content2: 'hello world',
       reply: ''
     }
   },
@@ -27,6 +43,15 @@ export default {
       this.$callMain('example.hello', value).then(r => {
         self.$message.info(r);
       })
+    },
+    executeJSHandle(value) {
+        executeJS({str: value}).then(res => {
+          if (res.code == 0) {
+            console.log(res.data);
+          }
+        }).catch(err => {
+          console.log('err:', err)
+        })
     }
   }
 }