5

I'm trying out using GWT's ScriptInjector for the first time, and was wondering why I can't see the injected script as a tag anywhere in the page when I view page source. I'd expect it to show up in the page head.

I'm using a dead simple example, which works in that it displays the alert. I'm just wondering why I can't physically see it injected in the page. Also if I declare a JavaScript variable inside my script, it doesn't seem available on the global scope.

ScriptInjector.fromString("window.alert('testing');")
.setWindow(ScriptInjector.TOP_WINDOW)
.inject();
1
  • You have just shared that is working. What is not working? Please share the code. Please have a look at my post. Commented Apr 7, 2014 at 18:58

2 Answers 2

7

ScriptInjector works by injecting your js snippet into the top level window object and, by default, remove it just after it got evaluated (if you used fromString(); with fromUrl() the element is not removed by default). This is why you do not see it, but it actually executes.

If you want to keep the injected script element, just use setRemoveTag(false) on your builder FromString object, i.e.:

ScriptInjector.fromString("window.alert('testing');")
  .setRemoveTag(false)
  .setWindow(ScriptInjector.TOP_WINDOW)
  .inject();
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, I didn't know that. Although even using fromUrl(), or fromString() with .setRemoveTag(false), I still don't see the injected script element in the page source. There are a lot of things going in in this app so maybe something else is going on here. I'll try with a simpler app and see if that works.
Actually, it does work with setRemoveTag(false). Just missed it in between various other things on the page. Thanks!
0

Please have a look at below sample.

I have modified the inner HTML of a div. The changes are visible in Firebug but if you view the source it will be not there.

EntryPointClass:

ScriptInjector.fromString("document.getElementById('mydiv').innerHTML='hi';")
            .setWindow(ScriptInjector.TOP_WINDOW).inject();

HTML:

<html>
 ...
    <body>
        <div id='mydiv'></div>  
    </body>
 ...
</html>

Snapshot:

enter image description here

View Source:

enter image description here

2 Comments

Thanks for the reply. I guess I'm expecting to see an actual <script> tag in the page head, which I'm not seeing (even if I use setRemoveTag(false)).
Actually was just being dumb, it does work. And also was earlier stupidly not looking in the firebug html tab.

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.