管道通过命令行生成javascript

时间:2015-10-08 08:13:50

标签: javascript php shell pipe phantomjs

我们使用PhantomJS来创建网页的屏幕截图。它是从命令行运行的,因为某些原因php-phantomjsscreen-master在我们的服务器上不起作用。解决方案是使用PHP shell_exec()命令运行命令行脚本。

PhantomJS使用一个javascript文件,它告诉您要做什么,要加载哪个页面以及写入文件的位置。由于多个用户将使用此功能,我需要将用户ID或其他内容传递到javascript文件,因此它可以加载用户特定页面并使用名称中的用户ID保存屏幕截图。

一种选择是通过PHP生成javascript,然后使用它。请使用以下javascript:

var id = 1234;
var page = require('webpage').create();
page.viewportSize = { width: 1024, height: 768 };
page.clipRect = { top: 0, left: 0, width: 1024, height: 768 };
page.open('http://test.local/screenshot.php?id='+id, function(status) {
  console.log("Status: " + status);
  if(status === "success") {
    page.render('/var/www/test/tmp/screenshot-'+id+'.png');
  }
  phantom.exit();
});

shell命令是这样的:

/path/to/phantomjs /var/www/test/js/phantom.js

变量id的值为1234。此值不是固定的,而是每个用户的更改。 javascript文件不是动态的,但可以使用PHP生成。我可以生成javascript文件,或者只生成脚本。

我可以通过命令行将此生成的脚本(或文件)传输到PhantomJS吗?

我还有哪些其他选项可以更好地使其正常工作?

1 个答案:

答案 0 :(得分:1)

如果你想将命令args发送到pj,你可以这样做:

 var system = require('system');
    var page = require('webpage').create();
    page.open(system.args[1], function () {
        page.paperSize = { format: 'A4', orientation: 'landscape'};
        window.setTimeout(function(){
            page.render(system.args[2]);
            phantom.exit();
        },300);
    });

在php中:

$cmd = 'phantomjs '.$path. 'render.js '.$html_tpl.' '. $image;
exec($cmd);