0

In GWT how do I make this Javascript into a ScriptElement:

<script type="text/javascript">
var addthis_config = addthis_config||{};
addthis_config.pubid = 'YOUR-PUBID';
$.getScript( "https://s7.addthis.com/js/300/addthis_widget.js#domready=1");
</script>

The solution I know is for:

  ScriptElement script = doc.createScriptElement();
  script.setSrc("https://s7.addthis.com/js/300/addthis_widget.js#domready=1");

However how about the addthis_config and addthis_config.pubid ?

1 Answer 1

2

After creating the ScriptElement you have to inject it to the DOM in order to load the 3rd-party script, but this is not the normal way to load scripts in GWT.

Normally in GWT we use the ScriptInjector, but in your case, you have to use previously some JSNI code to set those vars in the window object:

final static String AT_PUBID = "YOUR-PUBID";
final static String AT_URL = "https://s7.addthis.com/js/300/addthis_widget.js#domready=1";

public void onModuleLoad() {
  setAddthisId(AT_PUBID);
  ScriptInjector.fromUrl(AT_URL).inject();
}

private static native void setAddthisId(String id) /*-{
  $wnd.addthis_config = $wnd.addthis_config||{};
  $wnd.addthis_config.pubid = id;
}-*/;

You could even inject your javascript code as a string using ScriptInjector as well, but IMO this is a nasty solution since GWT compiler cannot perform any JSNI syntax checking:

....
ScriptInjector.fromString(
   "$wnd.addthis_config = $wnd.addthis_config||{};" +
   "$wnd.addthis_config.pubid = '+ " AT_PUBID + "';"
).inject();
ScriptInjector.fromUrl(AT_URL).inject();

If you actually prefer not to use JSNI at all to avoid dealing with javascript mistakes, I would suggest to use the gwtquery library, which apart from dozens of features allows you to manipulate DOM elements with a very simple syntax:

import static com.google.gwt.query.client.GQuery.*;
....

$(window).prop("addthis_config", $$("pubid: " + AT_PUBID));
ScriptInjector.fromUrl(AT_URL).inject();
Sign up to request clarification or add additional context in comments.

4 Comments

I'm trying to figure out how to set multiple variables with $(window)
Like window.var1 = 'a', window.var2 = 'b' ... ?
Yeah, exactly like that
With GQuery: $(window).prop("var1", "a"); $(window).prop("var2", "b");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.