GWT <script> tag not loading properly - java

I have defined in my head tag a function <script> functionX(a,b,c) ....</script>
which calls some third party js. The actual function is this:
<script>
function fbc(d, s, id)
{ var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}
</script>
and later on I want to call that function. I'm calling it using and HTML widget in the following way:
HTML html = new HTML();
setHTML(
"<script>"+
" fbcomment(document, 'script', 'facebook-jssdk'); "+
"</script> "+
"<fb:comments width=\"600\" num_posts=\"2\" href=\"http://www.woojah.com\"></fb:comments>");
However, it is not executing properly. Any advice would be very useful.

It is more idiomatic to call external functions using JSNI:
native void facebookComment(Document d, String s, String id) /*-{
fbc(d, s, id);
}-*/;
void myFunction() {
facebookComment(Document.get(), "script", "facebook-jssdk");
}

Related

Android - Pass value from app to webview page not working

I`m just trying to pass values from my app to the webview using the examples from android developer page, throught javascript.
My webview is set with:
WebView navegador;
final JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(this);
navegador.getSettings().setJavaScriptEnabled(true);
navegador.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
navegador.addJavascriptInterface(myJavaScriptInterface, "navegador");
navegador.loadUrl(url);
Right under it i create the JavaScriptInterface class:
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
System.out.println("FaceWeb -> Navegador.java -> JavascriptInterface");
mContext = c;
}
public String getLogin(){
System.out.println("FaceWeb -> Navegador.java -> getLogin: "+b.getString("login"));
return b.getString("login");
}
public String getNome(){
System.out.println("FaceWeb -> Navegador.java -> getNome: "+ b.getString("nome"));
return b.getString("nome");
}
public Integer getId(){
System.out.println("FaceWeb -> Navegador.java -> getId: "+ b.getInt("id"));
return b.getInt("id");
}
}
And here my html:
<body>
<div id="teste">
Parado.
</div>
<input type="button" onclick="leitura()" value="Buscar Valores" />
<script type="text/javascript">
function leitura()
{
document.getElementById("teste").innerHTML = "Aguarde...";
var fonte = navegador.getLogin();
var id = navegador.getId();
var nome = navegador.getNome();
document.getElementById("teste").innerHTML = "Login: "+fonte + "<br>Nome: "+nome+"<br>ID: "+id;
}
</script>
</body>
In Eclipse log i can see that the functions getLogin, getId and getNome are called when the button is pressed on the webview, with right values, but my div "teste" remains with "Aguarde..." only and the button itself remains 'pressed'.
Any ideas please, reply. I really don`t know where to look anymore.
Try with public int getId() instead of Integer. Try with calling getLogin and getNome only. See if getId is the problemmaker. If you comment the last innerHtml out, does the button come up then?

How to get ArrayList data from action class inside a javascript?

I'm gong to making an autocompleter using jquery autocompleter. In my case I need to load some data from a method. That method(return a list) has a parameter and I need to pass the textfield input as the method argument. Is this possible? If it is how can I do this?
Method is,
public List<Item> getSuggestedData(String def) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select o from Item o WHERE o.itemName like :def");
q.setParameter("def", def + "%");
return q.getResultList();
} finally {
em.close();
}
}
index.jsp,
<script>
$(function() {
var availableTags = [/*I need to load data to here*/];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
<div class="ui-widget">
<s:textfield id="tags"/>
</div>
try this
$.ajax({
async:settings.Async,url:Url,cache:false,type:'POST',data:$("#tags").val()
}).done(function (result) {
$( "#tags" ).autocomplete({
source: result
});
});
jQuery is a client side script and java code is on server side. You need to send a HTTP request from client to the server to get your list of tags. You can do this by AJAX. jQuery has a good support for AJAX.

Passing id value to action class

I want to pass textfield with id value pat to the getautocomplete.action in Struts 2. Here I am using TINY.box to pop up the next page.
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
T$('tiny_patient').onkeypress = function(){
TINY.box.show('getautocomplete.action',1,0,0,1)
}
</script>
You need to append the id pat and its value to the url that you pass to the show function. For example
var url = 'getautocomplete.action?pat=' + $("#pat").val();
You can then use the variable url in your show function.
You also need to add the following in your action class. This also depends on the java type of pat. I am using String,
private String pat;
public String getPat()
{
return pat;
}
public void setPat(final String value)
{
this.pat = value;
}
Note
It is recommended to get your url using the following instead of hard-coding the extension
<s:url id="url_variable" namespace="/namespace_of_action" action="action_name" />
var url = '<s:property value="url_variable" />?pat=' + $("#pat").val();
If you are trying to populate the box based on previous box selection or any server side process you have to use ajax.
In your action class , write a getter-setter for variable named "pat" like this:
private string pat;
public getPat()
{
.........
}
public setPat(String pat)
{
this.pat=pat;
}
and change
TINY.box.show('getautocomplete.action',1,0,0,1)
to
TINY.box.show('getautocomplete.action?pat="xyz"',1,0,0,1)
Hope this will solve your problem unless you have an idea about ajax.
Try
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
document.getElementById("tiny_patient").onkeypress = function(e){
TINY.box.show("<s:url action='getautocomplete'/>"+"?pat="+document.getElementById("pat").value,1,0,0,1)
}
</script>

use deployJava.js to call java methods in javascript

I want to call java methods in javascript and Andrew Thompson suggested to use the deployJava.js library for this. I followed these instructions:
http://docs.oracle.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html
Here is explained how to use the java class in javascript, but I would like to call the java methods from within the javascript. (This is because I want to import a .owl file in java en export the information in json-format to my code written in javascript.)
Does anybody know how to do this with the deployJava library?
This is my code to import the java file:
<noscript>A browser with JavaScript enabled is required for this page to operate properly.</noscript>
<h1>Sending Messages to Other Applets</h1>
<script>
function sendMsgToIncrementCounter() {
receiver.incrementCounter();
}
</script>
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'Sender.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'../Receiver.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
and this is are the sender and receiver java files:
import javax.swing.*;
public class Receiver extends JApplet {
private int ctr = 0;
private JLabel ctrLbl = null;
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
ctrLbl = new JLabel("");
add(ctrLbl);
}
});
} catch (Exception e) {
System.err.println("Could not create applet's GUI");
}
}
public void incrementCounter() {
ctr++;
String text = " Current Value Of Counter: " + (new Integer(ctr)).toString();
ctrLbl.setText(text);
}
}
import javax.swing.*;
import java.awt.event.;
import netscape.javascript.;
public class Sender extends JApplet implements ActionListener {
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
final ActionListener al = this;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JButton btn = new JButton("Click To Increment Counter");
add(btn);
btn.addActionListener(al);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
public void actionPerformed(ActionEvent e) {
try {
JSObject window = JSObject.getWindow(this);
window.eval("sendMsgToIncrementCounter()");
} catch (JSException jse) {
jse.printStackTrace();
}
}
}
I just copy-paste this from the example given on this site:
http://docs.oracle.com/javase/tutorial/deployment/applet/iac.html
This example works perfect in my browser, so the way it is done is correct, but I suspect that I don't import the javafiles correct, since this are the errors from je java-console:
load: class Sender.class not found.
java.lang.ClassNotFoundException: Sender.class
at sun.plugin2.applet.Applet2ClassLoader.findClass(Applet2ClassLoader.java:195)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Plugin2ClassLoader.java:249)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:179)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:160)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Plugin2ClassLoader.java:690)
at sun.plugin2.applet.Plugin2Manager.createApplet(Plugin2Manager.java:3045)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Plugin2Manager.java:1497)
at java.lang.Thread.run(Thread.java:680)
Exception: java.lang.ClassNotFoundException: Sender.class
Combining your original method, with the new JS snippet, and part of the accepted answer on your last question (tweaked), gives..
<html>
<head>
<script>
// dangerous to have a 0x0 applet! Some security plug-ins regard it
// as suspicious & automatically remove the element. Better to set it
// not visible using styles
var attributes = {
codebase:'../sesame',
code:'applet_test',
width:10,
height:10
};
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);
function test() {
var app = document.applet_test;
alert("Screen Dimension\r\n width:" + app.getScreenWidth()
+ " height:" + app.getScreenHeight());
}
</script>
<body>
<FORM>
<INPUT
type="button"
value="call JAVA"
onClick = "test()">
</FORM>
<script>
deployJava.runApplet(attributes, parameters, version);
</script>
</body>
</html>
But I just wrote that up off the top of my head. Don't trust me, trust a validation service. ;)
I would advise setting up a simple webservice that your javascript code can use. It doesn't need to be very involved, personally I'd use a simple REST layout with JAX-RS (jersey is really nice to work with), especially if you want something simple with JSON support built-in (with the right plugin).
Trying to actually communicate with the applet on the page might be possible, but very browser dependent and IMHO not worth the hassle. If you're working on the web, might as well use a web service.
There was a problem with the directory of the .class files given in the attributes. Here is the correct code:
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'sesame/Sender.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'sesame/Receiver.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>

How to integrate Google Analytics into GWT using the asynchronous script

I'm trying to track pages using Google Analytics within a GWT application.
I already check the following thread: Integrating Google Analytics into GWT application
I think that the solution:
public static native void recordAnalyticsHit(String pageName) /*-{
$wnd.pageTracker._trackPageview(pageName);}-*/;
only works using the synchronous GA script.
I'm trying with the following:
public native void trackHit (String pageName) /*-{
try {
$wnd._gaq.push (['_setAccount', 'UA-XXXXXX-XX']);
$wnd._gaq.push (['_setDomainName', '.mydomain.com']);
$wnd._gaq.push (['_trackPageview', pageName]);
} catch (err) {
alert('failure on gaq' + err);
}
}-*/;
And is not working for me.
Here are my page- and event-tracking functions:
public static native void trackEvent(String category, String action, String label) /*-{
$wnd._gaq.push(['_trackEvent', category, action, label]);
}-*/;
public static native void trackEvent(String category, String action, String label, int intArg) /*-{
$wnd._gaq.push(['_trackEvent', category, action, label, intArg]);
}-*/;
public static native void trackPageview(String url) /*-{
$wnd._gaq.push(['_trackPageview', url]);
}-*/;
I do the _setAccount stuff like normal in the host page (needs to execute before trackPageview() etc will work:
<!-- Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-FAKE1234-2']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
You don't need to use setAccount every time you post an event, only at the beginning. I don't bother with try{}catch{} stuff... I don't actually know JavaScript.
There is a new version of Google Analytics out which uses a new analytics.js script. It's the same process though, just add the script in your html header:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-YOUR_ACCOUNT-X', 'auto');
ga('send', 'pageview');
</script>
And then can call the new methods like so:
public static native void googleAnalyticsTrackPageView(String url) /*-{
$wnd.ga('send', 'pageview', url);
}-*/;
there is a project on goole code called gwt-gatracker that implement GA function to use in GWT projects. check it out here

Categories