Can I create a 'window' object for javascript running in the Java6 Rhino Script Engine

走远了吗. 提交于 2019-11-30 05:11:44

问题


  • I want to run some Javascript on my Java6 server - i.e. using the javax.script API, specifically the Rhino Script Engine. (Although another solution would be acceptable)
  • The script file is created & supported by a third party, so I don't want to download it and edit it in case it changes over time.
  • The script directly references the 'window' object ( and probably the 'document' object etc. ) which Rhino does not seem to support.

Can I do this, and if so, how?


回答1:


var window = {}
var document = {}

... of course, they won't do a lot of good unless you populate them with the properties that the script is trying to access.

You can't just populate them with the standard browser APIs - most of them don't make sense outside the context of the browser.




回答2:


The window and document objects are just provided by web-browsers and are not part of the ECMAScript standard which Rhino implements. They are there to allow a script to access the current browser window and the HTML document. The document object is actually an implementation of the W3C DOM.

Rhino is a pure implementation of ECMAScript/JavaScript 1.7 and therefore does not know anything about HTML pages, windows and browserstuff in general. It is a general purpose scripting language which just happens to be mostly embedded into a web browser and thus you can usually use the global objects provided by the browser.

You can of course define some globally accessible objects with the names "window" and "document" which are just stubs which do nothing, but the script you want to execute probably uses some methods and/or properties on them, so this won't help you much. If you want to execute a script, which was written for execution in a browser environment, you need to provide a full "browser"-like environment.

If that is possible and makes sense in a server context is another question...



来源:https://stackoverflow.com/questions/964392/can-i-create-a-window-object-for-javascript-running-in-the-java6-rhino-script

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