문제

I am using javax.script in Java, and I'd like to be able to detect whether the current Javascript implementation is Rhino. I'm doing this because I need to script to work properly on web pages as well as in Rhino.

Javascript pseudocode:

function writeMessage(message) {
    if (implementation is Rhino) {
        print(message);
    }
    else if (script is running in a web browser) {
        document.write(message);
    }
}
도움이 되었습니까?

해결책

Ah, there we've got it in your comment. Just use the feature detection:

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

And then use writeMessage(string) all over your script. This is a short form of

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

which is better than what you suggested in the question, where the detection would be applied every time the function is invoked:

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

다른 팁

If it's only to be run in either the web browser or on top of Rhino, then surely they're mutually exclusive; that is, if the script is not running in a browser, then it's running via Rhino.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top