简体   繁体   English

电子:加载外部脚本并将其传递给函数

[英]Electron: loading an external script and passing it into a function

I am building an Atom Electron app. 我正在构建一个Atom Electron应用程序。 Right now I have this in the preload.js of one of my webviews: 现在我在我的一个webview的preload.js中有这个:

var { requireTaskPool } = require('electron-remote');
var work = '';
var _ = require('lodash');

work = requireTaskPool(require.resolve('./local/path/to/js/file.js'));


function scriptRun() {
  console.log('Preload: Script Started');
  // `work` will get executed concurrently in separate background processes
  // and resolve with a promise
  _.times(1, () => {
    work(currentTab).then(result => {
      console.log(`Script stopped. Total time running was ${result} ms`);
    });
  });
}
module.exports = scriptRun;
scriptRun();

It gets a local script and then executes it in a background process. 它获取一个本地脚本,然后在后台进程中执行它。

I want to do the same exact thing, except I want to retrieve the script from an external source like so 我想做同样的事情,除了我想从外部源检索脚本,如此

work = requireTaskPool(require.resolve('https://ex.com/path/to/js/file.js'));

When I do this, I get errors like: 当我这样做时,我得到的错误如下:

Uncaught Error: Cannot find module 'https://ex.com/path/to/js/file.js'

How can I load external scripts? 如何加载外部脚本? And then use the loaded scripts with my work function. 然后使用我的work函数加载脚本。 My feeling is that require only works with local files. 我的感觉是只需要使用本地文件。 If AJAX is the answer, can I see an example of how to get a script, then pass it into my work without executing it prior? 如果AJAX是答案,我可以看一个如何获取脚本的例子,然后将其传递给我的work而不先执行它吗?

You have not provided any details on your file.js. 您尚未提供有关file.js的任何详细信息。 But I can give you the general idea. 但我可以给你一般的想法。

There are two things that you need at minimum to call your package a module: 您至少需要两件事来调用包模块:

  1. file.js (of course you have it) and file.js(当然你有)和
  2. package.json 的package.json

The structure of your file.js should be something like this: file.js的结构应该是这样的:

//load your dependencies here

var something = require("something");

//module.exports is necessary to export your code, 
//so that you can fetch this code in another file by using require.

module.exports = function() {
    abc: function(){
         //code for abc function
    },
    xyz: function(){
         //code for xyz function
    }
}

Now if you put your package on any website, you can access it as: 现在,如果您将包裹放在任何网站上,您可以访问它:

npm install https://ex.com/path/to/js/file.js

Now, a copy of your package will be put into node-modules folder. 现在,您的包的副本将被放入node-modules文件夹中。

So, now you can access it as: 所以,现在您可以访问它:

var x = require('name-of-your-package-in-node-modules');

Now, you can also do: 现在,你也可以这样做:

var abc = require('name-of-your-package-in-node-modules').abc;

or 要么

var xyz = require('name-of-your-package-in-node-modules').xyz;

I was able to load a remote js file and execute the function defined in it, hopefully it will provide you enough to start with... 我能够加载远程js文件并执行其中定义的函数,希望它能为您提供足够的开始...

my remote dummy.js, available online somewhere: 我的远程dummy.js,在线提供:

const dummy = () => console.log('dummy works');

my download.js: 我的download.js:

const vm = require("vm");
const rp = require('request-promise');

module.exports = {
    downloadModule: async () => {
        try {
            let body = await rp('http://somewhere.online/dummy.js');
            let script = vm.createScript(body);
            script.runInThisContext();

            // this is the actual dummy method loaded from remote dummy.js
            // now available in this context:
            return dummy;

        } catch (err) {
            console.log('err', err);
        }
        return null;
    }
};

You need to add the request-promise package. 您需要添加request-promise包。

Then in my main.js I use it like this: 然后在我的main.js中我使用它:

const {downloadModule} = require('./download');

downloadModule().then((dummy) => {
    if (dummy) dummy();
    else console.log('no dummy');
});

When I run it, this is what I get: 当我运行它时,这就是我得到的:

$ electron .

 dummy works

I wanted to create an actual module and require it, but I have not had the time to play with this further. 我想创建一个实际模块并要求它,但我没有时间进一步使用它。 If I accomplish that I will add it here. 如果我完成了,我会在这里添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM