Interpreting JavaScript in PHP

怎甘沉沦 提交于 2019-12-03 23:48:39
Hamish

It's an interesting question and the down-voters are being unimaginative about potential use-cases. Page archiving tools, printing scripts, preview images - all valid reasons to want to manipulate a document with the JavaScript included within the page.

I'm not aware of any existing PHP implementations, but you could probably adapt Mozilla's SpiderMonkey as a PHP module, or as a standalone tool to manipulate a DOMDocument and return the result.

I haven't had experience with server-side JavaScript, but some issues that I believe might need to be dealt with:

  • Host objects like document and window are not part of the ECMAScript specification (these are objects provided by the implementing browser) so you need to make sure that the library provides equivalent host objects.
  • You might have security issues around executing client side scripts within a server side environment. This is a lot like allowing the user to submit a PHP script to be evaluation, so you need to make sure the security sandbox is tight.

Another (perhaps) safer and easier to implement option might be to use a modified FireFox or WebKit instance that runs as a browser, loading up the target pages and returning the modified source to your application.

Pian0_M4n

From PHP 5.3 you can use V8JS extention from PHP. It's a native library that uses the new Google V8 Javascript engine to execute JS and return the result.

It's good because you can pass vars in PHP arrays and are interpreted very well

NodeJS (or some other derivative of google's v8) might actually be the best way to go here. If you're concerned about the various things nodejs can do (eg. sockets, etc), you can probably "strip it down" by removing modules and/or addons -- I think even the built in stuff is ultimately implemented in such a way that it could be stripped out fairly easily.

An alternate approach might be to simply replace, override, or remove the require function from node.js.

There's also envjs which should make it easier to run js that was designed to run the browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!