Determine whether the current Javascript implementation is Rhino
-
24-06-2021 - |
문제
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.
제휴하지 않습니다 StackOverflow