java - 判断当前Javascript实现是否是Rhino

标签 java javascript rhino javax.script

我在Java中使用javax.script,我希望能够检测当前的Javascript实现是否是Rhino。我这样做是因为我需要编写脚本才能在网页和 Rhino 中正常工作。

Javascript 伪代码:

function writeMessage(message) {
    if (implementation is Rhino) {
        print(message);
    }
    else if (script is running in a web browser) {
        document.write(message);
    }
}

最佳答案

啊,我们已经在您的评论中看到了。只需使用特征检测即可:

var writeMessage = document && document.write
  ? document.write.bind(document)
  : print;

然后在整个脚本中使用writeMessage(string)。这是short form

if (document && document.write)
    var writeMessage = function(message) { document.write(message); };
else
    var writeMessage = function(message) { print(message); };

这比您在问题中建议的更好,每次调用函数时都会应用检测:

function writeMessage(message) {
    if (document && document.write) { // running in a web browser
        document.write(message);
    } else { // it will be Rhino
        print(message);
    }
}

关于java - 判断当前Javascript实现是否是Rhino,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11818833/

相关文章:

java - 在 URL 中使用 # 作为值键

java - Unicode 字符未打印在终端窗口上

java - PreUpdate 监听器在空更新期间触发

javascript - 减少表单垃圾邮件

javascript - 在 java 中安全运行 javascript 代码

javascript - 后处理 Wicket 响应(Rhino、jQuery)

java - 在 Java 中查找 List 中具有重复项的唯一元素

javascript - Node.js、Socket.io : How to get client browser-language?

javascript - 单击按钮时动态更新样式,D3 条形图

java - 如何使用 Rhino 桥接包含重载方法且可在 JavaScript 中索引的 Java 类?