M. S.
M. S.

Reputation: 109

Display HTML code with JS in GWT

I want to create a page based on HTML code in GWT. This code has some js code and its created from String object. I create the HTML object in my widget:

  @UiField
  HTML htmlCont;

and put the String with HTML to content:

htmlCont.setHTML(htmlCode);

It generally works, but js code isn't interpreted and when i try put something like this:

<p>Click the button to display an alert box:</p>

<button onclick="clickFun()">Try it</button>

<script>
function clickFun() {
    alert("I am an alert box!");
}
</script>

In my browser i get error:

Uncaught ReferenceError: clickFun is not defined

What I'm doing wrong?

Upvotes: 1

Views: 586

Answers (1)

Baz
Baz

Reputation: 36884

You can't add Javascript code with an HTML element, it's not going to be executable.

Use the ScriptInjector to add the Javascript:

String scriptBody = "var foo = ...";
ScriptInjector.fromString(scriptBody).inject();

Ideally you should create the widgets or elements yourself and use GWT methods to attach handlers to them or use JSNI.

Upvotes: 1

Related Questions