在javascript函数中执行puppeteer代码

时间:2018-05-27 07:25:30

标签: javascript electron puppeteer

嗯..我是puppeteerelectron的新手。

我有一个基本的木偶操作码,如下所示:

const puppeteer = require('puppeteer');


(async () => 
{
    const browser = await puppeteer.launch({ headless: false });

    const page = await browser.newPage();
    await page.setViewport({ width: 1366, height: 768});

    await page.goto('https://www.google.co.in', {waitUntil: 'networkidle2'});

})();

那很好。现在我不想在我的电子应用程序启动时打开浏览器。相反,我想在特定事件和javascript函数中打开它。每当我想要的时候会被调用。如下:

global.RunCommand = function(param)
{
    const browser = await puppeteer.launch({ headless: false });

    const page = await browser.newPage();
    await page.setViewport({ width: 1366, height: 768});

    await page.goto('https://www.google.co.in', {waitUntil: 'networkidle2'});


    return 'Done : ' + param;
}

抛出:

const browser = await puppeteer.launch({ headless: false });
                    ^^^^^^^^^

SyntaxError: Unexpected identifier
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:606:28)
at Object.Module._extensions..js (module.js:653:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:504:12)
at Function.Module._load (module.js:496:3)

任何帮助都将受到赞赏并提前致谢。

1 个答案:

答案 0 :(得分:3)

global.RunCommandasync函数,您必须始终在异步函数中声明 async

global.RunCommand = async function(param)
{
 ...
}