I am new to Gwt,i m implementing a webclipper project so my task to send some parameters from javascript file to Gwt so that i will be able to make the connection with my couchdb database but i am getting a problem in passing parameters like title, url ,and summary from webpage to Gwt n then couchdb.The following code is my javascript code:-
function onPageInfo(o) {
document.getElementById('title').value = o.title;
document.getElementById('url').value = o.url;
document.getElementById('summary').innerText = o.summary;
}
// Global reference to the status display SPAN
var statusDisplay = null;
// POST the data to the server using XMLHttpRequest
function addBookmark() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = "http://127.0.0.1:8888/practice.html? gwt.codesvr=127.0.0.1:9997&gwt.codesvr=127.0.0.1:9997/?title=1&url=2&summary=3";
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed
var title = encodeURIComponent(document.getElementById('title').value);
var url = encodeURIComponent(document.getElementById('url').value);
var summary = encodeURIComponent(document.getElementById('summary').value);
var tags = encodeURIComponent(document.getElementById('tags').value);
var params = 'title=' + title +
'&url=' + url +
'&summary=' + summary +
'&tags=' + tags;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/json');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
window.setTimeout(window.close, 1000);
} else {// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
}
// When the popup HTML has loaded
window.addEventListener('load', function(evt) {
// Handle the bookmark form submit event with our addBookmark function
document.getElementById('addbookmark').addEventListener('submit', addBookmark);
// Cache a reference to the status display SPAN
statusDisplay = document.getElementById('status-display');
// Call the getPageInfo function in the background page, injecting content_script.js
// into the current HTML page and passing in our onPageInfo function as the callback
chrome.extension.getBackgroundPage().getPageInfo(onPageInfo);
});
Thanks.....
You can call a function defined in a java file (of GWT client module) by exporting that function. Let's assume there is a class A.java which is also your entry point class. This class contains someMethod() which you need to call from javascript passing some parameters. The content of your class A would be something like
public class A implements EntryPoint {
public static functionExported = false;
public void onModuleLoad() {
ExportToBeCalledFromJs();
// other code goes here
}
public static native void ExportToBeCalledFromJs() /*-{
$wnd.toBeCalledFromJs = $entry(function(s1, s2) {
return #com.practice.gwt.client.A::someFunction();
});
#com.practice.gwt.client.A:functionExported = true;
}-*/;
}
Above code exports the function and makes it available to javascript. You can simply call toBeCalledFromJs(param1, param2) fromyour js where param1 would substitute s1 and param2 would substitute s2. If you wish to add more parameters you can modify $entry(function(s1, s2) in the code above.
Related
I'm trying to update an HTML5 table in real-time with some data from the database. Here is my code:
HTML page:
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("[some address]/api/sse");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("placeholder").innerHTML=table;
};
}
else {
[erro message]
}
</script>
And my Java Restful service:
#Path("/sse")
public class SSEResource {
#Context
private UriInfo context;
public SSEResource() {
}
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
public String getServerSentEvents() throws Exception {
SomeObject o = new SomeObject();
final String myString = o.someQuery().getEntity().toString();
return "data: " + myString + "\n\n";
}
}
This someQuery() method queries from database and returns what I want to put on my table. Everythings looks great. But I want to know if it's right or wrong, because if I put some log on someQuery() method, I see that every 3 seconds the query is executed. This may cause heavy duty, right? Is this normal or is my code wrong?
I want to observe the upload percentage of a file upload from GWT.
In JavaScript you can use a XMLHttpRequest and add an event listener like this:
var oReq = new XMLHttpRequest();
oReq.upload.addEventListener("progress", updateProgress, false);
// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
// ...
} else {
// Unable to compute progress information since the total size is unknown
}
}
(The above code is from here.)
This is also done very easily in jQuery as:
var $request = $.ajax({
xhr: function() {
xhrNativeObject = new window.XMLHttpRequest();
//Upload progress
xhrNativeObject.upload.addEventListener("progress", function(event) { ... }
}
});
I want to do the same with GWT. I could use a RequestBuilder to send a request, but this is only a high level wrapper around the XMLHttpRequest JavaScriot object. Another possibility would be to use the GWT XMLHttpRequest class which is a JSNI wrapper of the JavaScript XMLHttpRequest.
My problem:
How can I add a progress listener to the XMLHttpRequest or the RequestBuilder?
I used before gwt-upload library.
You dont need to rediscover America.
Thanks for moxie group
gwt-upload-project page
//upload spring service conroller
#RequestBody public void uploadImage(#RequestParam("file") MultipartFile file ){
//what ever you want
}
XML Configuration
<bean id=multipartResolver" class ="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
GWT Elemental contains all you need already AFAICT.
How do we call javascript from Android? I have this javascript library which I would like to use, I want to call the javascript function and pass the result value to the android java code. Haven't found the answer from now. i managed to call android code from javascript, but I want the other way around.
There is a hack:
Bind some Java object so that it can be called from Javascript with WebView:
addJavascriptInterface(javaObjectCallback, "JavaCallback")
Force execute javascript within an existing page by
WebView.loadUrl("javascript: var result = window.YourJSLibrary.callSomeFunction();
window.JavaCallback.returnResult(result)");
(in this case your java class JavaObjectCallback should have a method returnResult(..))
Note: this is a security risk - any JS code in this web page could access/call your binded Java object. Best to pass some one-time cookies to loadUrl() and pass them back your Java object to check that it's your code making the call.
You can use Rhino library to execute JavaScript without WebView.
Download Rhino first, unzip it, put the js.jar file under libs folder. It is very small, so you don't need to worry your apk file will be ridiculously large because of this one external jar.
Here is some simple code to execute JavaScript code.
Object[] params = new Object[] { "javaScriptParam" };
// Every Rhino VM begins with the enter()
// This Context is not Android's Context
Context rhino = Context.enter();
// Turn off optimization to make Rhino Android compatible
rhino.setOptimizationLevel(-1);
try {
Scriptable scope = rhino.initStandardObjects();
// Note the forth argument is 1, which means the JavaScript source has
// been compressed to only one line using something like YUI
rhino.evaluateString(scope, javaScriptCode, "JavaScript", 1, null);
// Get the functionName defined in JavaScriptCode
Object obj = scope.get(functionNameInJavaScriptCode, scope);
if (obj instanceof Function) {
Function jsFunction = (Function) obj;
// Call the function with params
Object jsResult = jsFunction.call(rhino, scope, scope, params);
// Parse the jsResult object to a String
String result = Context.toString(jsResult);
}
} finally {
Context.exit();
}
You can see more details at my post.
In order to match the method calls of the iOS WebviewJavascriptBridge ( https://github.com/marcuswestin/WebViewJavascriptBridge ), I made some proxy for the calls of register_handle and call_handle. Please note I am not a Javascript-guru therefore there is probably a better solution.
javascriptBridge = (function() {
var handlers = {};
return {
init: function () {
},
getHandlers : function() {
return handlers;
},
callHandler : function(name, param) {
if(param !== null && param !== undefined) {
JSInterface[name](param);
} else {
JSInterface[name]();
}
},
registerHandler : function(name, method) {
if(handlers === undefined) {
handlers = {};
}
if(handlers[name] === undefined) {
handlers[name] = method;
}
}
};
}());
This way you can send from Javascript to Java calls that can have a String parameter
javascriptBridge.callHandler("login", JSON.stringify(jsonObj));
calls down to
#JavascriptInterface
public void login(String credentialsJSON)
{
Log.d(getClass().getName(), "Login: " + credentialsJSON);
new Thread(new Runnable() {
public void run() {
Gson gson = new Gson();
LoginObject credentials = gson.fromJson(credentialsJSON, LoginObject.class);
SingletonBus.INSTANCE.getBus().post(new Events.Login.LoginEvent(credentials));
}
}).start();
}
and you can call back to Javascript with
javascriptBridge.registerHandler('successfullAuthentication', function () {
alert('hello');
})
and
private Handler webViewHandler = new Handler(Looper.myLooper());
webViewHandler.post(
new Runnable()
{
public void run()
{
webView.loadUrl("javascript: javascriptBridge.getHandlers().successfullAuthentication();"
}
}
);
If you need to pass a parameter, serialize to JSON string then call StringEscapeUtils.escapeEcmaScript(json), otherwise you get unexpected identifier: source (1) error.
A bit tacky and hacky, but it works. You just have to remove the following.
connectWebViewJavascriptBridge(function(bridge) {
}
EDIT:
in order to change the global variable to an actual property, I changed the above code to the following:
(function(root) {
root.bridge = (function() {
var handlers = {};
return {
init: function () {
},
getHandlers : function() {
return handlers;
},
callHandler : function(name, param) {
if(param !== null && param !== undefined) {
Android[name](param);
} else {
Android[name]();
}
},
registerHandler : function(name, method) {
if(handlers === undefined) {
handlers = {};
}
if(handlers[name] === undefined) {
handlers[name] = method;
}
}
};
}());
})(this);
I got the idea from Javascript global module or global variable .
For a full implementation of JavaScript that doesn't require using a slow WebView, please see AndroidJSCore, which is a full port of Webkit's JavaScriptCore for Android.
UPDATE 2018: AndroidJSCore is deprecated. However, its successor, LiquidCore has all of the same functionality and more.
Calling functions from Android is very simple:
JSContext context = new JSContext();
String script =
"function factorial(x) { var f = 1; for(; x > 1; x--) f *= x; return f; }\n" +
"var fact_a = factorial(a);\n";
context.evaluateScript("var a = 10;");
context.evaluateScript(script);
JSValue fact_a = context.property("fact_a");
System.out.println(df.format(fact_a.toNumber())); // 3628800.0
I am using a getJson call for drop downs. I want to have an image preloading effect for this ajax call.
Can any one help me out with this...??
My code follows:
$.getJSON("myAction.do?method=fetchThruAJAX", {
TypeNo: $("#Type").val(),
ajax: 'true'
}, function(j) {
var options = '<option selected value="-1">---Select---</option>';
if (j != null) {
$.each(j.Model, function(i, item) {
options += '<option value="' + item.SeqNo + '">'
+ item.Name + '</option>';
});
}
$("select#Model").html(options);
});
You can do that globally using the ajaxStart and ajaxStop events:
$("#yourEffectContainerID").ajaxStart(function() {
$(this).fadeIn("fast");
}).ajaxStop(function() {
$(this).fadeOut("fast");
});
That way, your effect container will be displayed during all AJAX requests (so that behavior is not limited to the specific getJSON() call you issue for your dropdown).
I have a web application that uses java applet defined in a <applet> tag. Is it possible to add a javascript event that is triggered after the applet is fully loaded? This is some initialization javascript that is dependent on that the applet is fully loaded and valid.
javascript invoking is rather simple:
Your init() method can include the jsObject declaration and javascript invoking:
#Override
public void init() {
// some code
JSObject jsObject = JSObject.getWindow(this);
jsObject.eval("your javascript");
}
If you don't have source code control over the applet, you can poll for the applet to be loaded before calling methods on it. Here is a utility function I wrote that does just that:
/* Attempt to load the applet up to "X" times with a delay. If it succeeds, then execute the callback function. */
function WaitForAppletLoad(applet_id, attempts, delay, onSuccessCallback, onFailCallback) {
//Test
var to = typeof (document.getElementById(applet_id));
if (to == 'function' || to == 'object') {
onSuccessCallback(); //Go do it.
return true;
} else {
if (attempts == 0) {
onFailCallback();
return false;
} else {
//Put it back in the hopper.
setTimeout(function () {
WaitForAppletLoad(applet_id, --attempts, delay, onSuccessCallback, onFailCallback);
}, delay);
}
}
}
Call it like this:
WaitForAppletLoad("fileapplet", 10, 2000, function () {
BuildTree("c:/");
}, function () {
alert("Sorry, unable to load the local file browser.");
});
You have an initializer function (i think it is run) in java applet. From there you can call a javascript in the web page after initialization work.
To work you must add the MAYSCRIPT attribute to your applet definition
<applet id="someId" code="JavaApplet.class" codebase="/foo" archive="Applet.jar" MAYSCRIPT>
</applet>
Code example to invoke a JavaScript:
public String invokeJavaScript(Object caller, String cmd) throws TiNT4Exception {
printDebug(2, "Start JavaScript >>" + cmd + "<<");
try {
// declare variables
Method getw = null;
Method eval = null;
Object jswin = null;
// create new instance of class netscape.javascript.JSObject
Class c = Class.forName("netscape.javascript.JSObject"); // , true, this.getClass().getClassLoader()); // does it in IE too
// evaluate methods
Method ms[] = c.getMethods();
for (int i = 0; i < ms.length; i ++) {
if (ms[i].getName().compareTo("getWindow") == 0) { getw = ms[i]; }
else if (ms[i].getName().compareTo("eval") == 0) { eval = ms[i]; }
} // for every method
printDebug(3, "start invokings");
Object a[] = new Object[1];
a[0] = caller;
jswin = getw.invoke(c, a);
a[0] = cmd;
Object result = eval.invoke(jswin, a);
if (result == null) {
printDebug(3, "no return value from invokeJavaScript");
return "";
}
if (result instanceof String) {
return (String)result;
} else {
return result.toString();
}
} catch (InvocationTargetException ite) {
throw new TiNT4Exception(ite.getTargetException() + "");
} catch (Exception e) {
throw new TiNT4Exception(e + "");
}
} // invokeJavaScript
You can use the param tag to pass the name of a JS function into your applet:
<applet id="myapplet" code="JavaApplet.class" codebase="/foo"
archive="Applet.jar" MAYSCRIPT>
<param name="applet_ready_callback" value="myJSfunction"/>
</applet>
In your applet, get the value of the param and call the function when ready:
#Override
public void init() {
String jsCallbackName = getParameter("applet_ready_callback");
JSObject jsObject = JSObject.getWindow(this);
jsObject.eval(jsCallbackName + "()");
}
I used another way to call a JavaScript function from an applet.
try {
getAppletContext().showDocument(new URL("javascript:appletLoaded()"));
} catch (MalformedURLException e) {
System.err.println("Failed to call JavaScript function appletLoaded()");
}
...must be called in the applet class which extends Applet or JApplet. I called the JavaScript function at the end of my start() method.
It is possible with Java 7 SE. You can register onLoad() event or just poll status, see Handling Initialization Status With Event Handlers for an example.
In order to use this functionality, you should deploy the applet with java_status_events parameter set to true.
The article Applet Status and Event Handlers outlines the status and events:
Status
LOADING = 1 - Applet is loading
READY = 2 - Applet has loaded completely and is ready to receive JavaScript calls
ERROR = 3 - Error while loading applet
Events
onLoad: Occurs when applet status is READY. Applet has finished loading and is ready to receive JavaScript calls.
onStop: Occurs when applet has stopped.
onError: Occurs when applet status is ERROR. An error has occurred while loading the applet.
You can register or determine an event handler in the JavaScript code of a web page as shown in the following code snippets.
// use an anonymous function
applet.onLoad(function() {
//event handler for ready state
}
// use a regular function
function onLoadHandler() {
// event handler for ready state
}
// Use method form
applet.onLoad(onLoadHandler);
// Use attribute form
applet.onLoad = onLoadHandler;