1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.host.event;
16
17 import org.htmlunit.corejs.javascript.BaseFunction;
18 import org.htmlunit.corejs.javascript.Context;
19 import org.htmlunit.corejs.javascript.Function;
20 import org.htmlunit.corejs.javascript.JavaScriptException;
21 import org.htmlunit.corejs.javascript.Scriptable;
22 import org.htmlunit.corejs.javascript.VarScope;
23 import org.htmlunit.html.DomElement;
24 import org.htmlunit.html.DomNode;
25 import org.htmlunit.html.HtmlPage;
26 import org.htmlunit.html.csp.ContentSecurityPolicy;
27 import org.htmlunit.javascript.JavaScriptEngine;
28
29
30
31
32
33
34
35 public class EventHandler extends BaseFunction {
36 private final DomNode node_;
37 private final String eventName_;
38 private final String jsSnippet_;
39 private Function realFunction_;
40 private boolean blockedByContentSecurityPolicy_;
41
42
43
44
45
46
47
48
49
50 public EventHandler(final VarScope scope, final DomNode node, final String eventName, final String jsSnippet) {
51 super(scope);
52 node_ = node;
53 eventName_ = eventName;
54 jsSnippet_ = jsSnippet;
55 }
56
57
58
59
60 @Override
61 public Object call(final Context cx, final Object nt, final VarScope scope,
62 final Object thisObj, final Object[] args)
63 throws JavaScriptException {
64
65
66
67
68
69
70
71
72 if (realFunction_ == null) {
73 if (blockedByContentSecurityPolicy_) {
74 return JavaScriptEngine.UNDEFINED;
75 }
76 if (node_ instanceof DomElement element
77 && element.getPage() instanceof HtmlPage page
78 && !ContentSecurityPolicy.allowsScriptAsAttribute(page, element, jsSnippet_)) {
79 blockedByContentSecurityPolicy_ = true;
80 return JavaScriptEngine.UNDEFINED;
81 }
82
83 final String js = "function on" + eventName_ + "(event) { " + jsSnippet_ + " \n}";
84 realFunction_ = cx.compileFunction(scope, js, eventName_ + " event for " + node_
85 + " in " + node_.getPage().getUrl(), 0, null);
86 realFunction_.setParentScope(scope);
87 }
88
89 return realFunction_.call(cx, scope, thisObj, args);
90 }
91
92
93
94
95
96
97
98
99 @Override
100 public Object getDefaultValue(final Class<?> typeHint) {
101 return "function on" + eventName_ + "(event) { " + jsSnippet_ + " }";
102 }
103
104
105
106
107 @Override
108 public Object get(final String name, final Scriptable start) {
109
110 if ("toString".equals(name)) {
111 return new BaseFunction(getParentScope()) {
112 @Override
113 public Object call(final Context cx, final Object nt, final VarScope scope,
114 final Object thisObj, final Object[] args) {
115 return "function on" + eventName_ + "(event) { " + jsSnippet_ + " }";
116 }
117 };
118 }
119
120 return super.get(name, start);
121 }
122 }