pveselov

Nashorn - @FunctionalInterface function

Oct 26th, 2021 (edited)
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1.  
  2. import jdk.nashorn.api.scripting.JSObject;
  3.  
  4. import javax.script.Bindings;
  5. import javax.script.ScriptContext;
  6. import javax.script.ScriptEngine;
  7. import javax.script.ScriptEngineManager;
  8. import java.util.function.Consumer;
  9.  
  10. class Scratch {
  11.  
  12.     public static void main(String[] args) throws Exception {
  13.  
  14.         ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
  15.  
  16.         Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
  17.         engineScope.put("window", engineScope);
  18.         engineScope.put("self", engineScope);
  19.         engineScope.put("parent", engineScope);
  20.         engineScope.put("opener", engineScope);
  21.         engineScope.put("top", engineScope);
  22.  
  23.         // http://mail.openjdk.java.net/pipermail/nashorn-dev/2013-December/002520.html
  24.         // https://stackoverflow.com/a/33376041/622266
  25.         engineScope.put("postMessage", (FakeWindow) (data, frameUrl) -> System.out.println("frame url:"+frameUrl));
  26.         engineScope.put("logString", (Consumer<String>)(s) -> System.out.println("simple:"+s));
  27.  
  28.         engine.eval("window.logString('something')");
  29.         engine.eval("window.postMessage({}, 'http://localhost');");
  30.  
  31.  
  32.     }
  33.  
  34.  
  35.     @FunctionalInterface
  36.     interface FakeWindow {
  37.  
  38.         void postMessage(JSObject data, String frameUrl);
  39.  
  40.     }
  41.  
  42. }
Add Comment
Please, Sign In to add comment