I'm trying to get a json data and a callback from javascript using webview.
I can get the json data but the problem is I cannot get the callback.
I need to fire the callback after a condition is met.
Android Code:
--------
// Adding the interface
webView.addJavascriptInterface(new WebAppInterface(this), "code");
--------
#JavascriptInterface
public void execute(String JsonData, String callback) {
String d = data; <---HAS JSON DATA RETURNED TO ANDROID
Log.d("jSon Data", d);
mCallback = callback; <---RETURNS "undefined"
}
Javascript code (I can't edit this.):
code.execute(JsonData, function(callback){
console.log(callback);
});
Android on button click
#OnClick(R.id.callback)
void onButtonCallback() {
String s = "Hello World";
// pass Hello World back to javascript. But I'm getting "undefined"
// for the callback
mCallback.passdata(s);
}
What I'm trying to achieve is:
1) Get data from Javascript to Android -> OKAY
2) Get the Callback from Javascript to Android -> Here's my problem
3) Fire the callback along with "hello world" string on button click
Note: I can't edit the javascript code. How am I going to achieve this? Do I need to inject Js from Android? If yes, how?
I just need to solve item number 2 to move forward. Thanks!
You can't do that. At least, based on my tests addJavascriptInterface() only works with primitive types and Strings, and so you cannot pass Javascript objects like functions.
I implement library with Google App Script and I have some difficulties to call a function from library using google.script.run.
Here is the code of my Library :
Code.gs
function ShowSideBar() {
var html = HtmlService.createTemplateFromFile('Index_librairie').evaluate()
.setTitle('Console de gestion')
.setWidth(300);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showSidebar(html);
}
function execution_appeler_par_html(){
Logger.log("execution_appeler_par_html");
}
Index_librairie.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
google.script.run.withSuccessHandler(work_off).execution_appeler_par_html();
function work_off(e){
alert(e);
}
</script>
</head>
<body>
test de ouf
</body>
</html>
Here is my Spreadsheet that use the Library :
Code.gs
function onopen() {
lbrairietestedouard.ShowSideBar();
}
Google.script.run does not reconize execution_appeler_par_html() function.
I should use libraryname.execution_appeler_par_html() but this syntaxe doesn't work in configuration of google.script.run
It seems that google.script.run can't look inside Objects or self-executing anonymous functions. In my case, putting any code inside an object or IIFE resulted in "is not a function" type of error being thrown in the console.
You can work around this by declaring a single function that will call nested methods inside libraries and objects.
.GS file
function callLibraryFunction(func, args){
var arr = func.split(".");
var libName = arr[0];
var libFunc = arr[1];
args = args || [];
return this[libName][libFunc].apply(this, args);
}
In JavaScript, every object behaves like an associative array of key-value pairs, including the global object that 'this' would be pointing to in this scenario. Although both 'libName' and 'libFunc' are of String type, we can still reference them inside the global object by using the above syntax. apply() simply calls the function on 'this', making the result available in global scope.
Here's how you call the library function from the client:
google.script.run.callLibraryFunction("Library.libraryFunction", [5, 3]);
I don't claim this solution as my own - this is something I saw at Bruce McPherson's website a while back. You could come up with other ad-hoc solutions that may be more appropriate for your case, but I think this one is the most universal.
Noticed the same problem trying to invoque library from google.script.run within HTML code.
Here is the workaround I use :
LIBRARY SIDE : aLibrary
function aFunction(){
//code...;
}
ADDON SIDE (requires library "aLibrary")
function aFunction(){
aLibrary.aFunction();
}
HTML
<input type="button" value="run aFunction" onclick="google.script.run.aFunction()" />
I like the workaround because I keep a clear view and organisation of my functions names, and do not need to alter HTML code if I bring my functions directly inside the addOn project, once development is satsifying.
Only thing I did not try yet : handling arguments and return values....
I hope this contribution is not to foolish, please forgive me I am very amateur...
After quite long time working on this, I found out that any function that you call from the library using google.script.run must exist in both the main script and the library script. The function must at least be declared in the main script while the implementation as well as the parameters are not important. The implementation will be in your library. If the main script does not include the name of the function, the error <your function> is not a function will appear.
Now that there is no meaning of having a library if every single function needs to exist in the main function, the solution provided by #Anton Dementiev would be used as a workaround. Suppose you have a function named testFunc in your library, you can call it using the following method:
google.script.run.callLibraryFunction("testFunc", [5, 3]);
where the library has this function:
function callLibraryFunction(func, args) {
args = args || [];
return this[func].apply(this, args);
}
and the main script has this declaration:
function callLibraryFunction() {
}
Google must fix this stupid behaviour
I am using QT 5.5 version.
I need to invoke javascript callback function from QT plugin with Structure/Object as argument. I could not modify HTML Application since it is not in our scope.
HTML application code snippet
var obj1 = document.getElementById('obj1_id'); //QT plugin object 1
var obj2 = document.getElementById('obj2_id'); //QT plugin object 2
obj2.init(obj1,callback); //QT API
function callback(arg1)
{
if ( obj1 === arg1){
// SUCCESS
else
// FAILURE
}
QT plugin code snippet
class::init(QWebElement obj, QString callback)
{
//need to Invoke callback with obj argument
}
Can any one help me on this?
Using Qt Signals and Slots -
In your javascript function -
add the following line -
myoperation.alert_script_signal.connect(callback);
In the Qt framework based C++ class - constructor, add the following line -
Register your Javascript callback --
view->page()->mainFrame()->addToJavaScriptWindowObject("myoperation", this);
// now invoke the callback from some method in that Qt class.
emit alert_script_signal();
You need to understand one thing that QtWebkit is the platform here. So, basically, the html, javascript is running on the Qt Webkit.
I have some examples - http://www.tune2wizard.com/linux-qt-callback-from-c-to-the-javascript-function/
I am trying to develop a plugin to internet explorer browser using csharp and I try to inject a javascript to the loaded page.
To inject the javascript i used the following code. The code is injected and the alert is working fine.
but code given below should return the value of "msg" to output.
when i run this code i get null value for output. kindly help.
var output= HTMLDocument.parentWindow.execScript("msg()","JScript");
function msg(){
var msg = "This is sample";
alert(msg);
return msg;
}
According to this page:
https://msdn.microsoft.com/en-us/library/ie/ms536420%28v=vs.85%29.aspx
The execCode method returns some sort of null value. Use eval if you want the value of msg().
IE cannot eval functions (Presumably for security reasons).
The best workaround is to put the function in an array, like this:
var func = eval('[' + funcStr + ']')
I want to make an ajax call that will return a json object. One of this JSON object's properties will be the string of a function to be executed in the client. I realise this can easily be solved by using eval, but seeing the many disadvantages of eval, I'd rather avoid it. My question is:
Can I in some way return from the server some js code and execute it without resorting to eval?
As requested, here's some example code:
Server (Node.js):
var testFunc = function() {
alert('h1');
};
app.get('/testPack', function(req, res) {
var template = jade.render('h1 hi');
res.send({
template : template,
entity : testFunc.toString(),
data : {
id: "OMG I love this"
}
});
});
Client:
$(document).ready(function() {
$.ajax({
url: '/testPack',
success: function(data) {
$('body').append($(data.template))
alert(data.data.id);
var entity = eval(data.entity);
entity();
}
})
})
Of course, the returned function called entity wouldn't do such a silly thing, it would expose an API of the returned widget.
Just to clarify, I'd like to avoid having to make a separate call for the javascript itself. I'd rather bundle it with the template and data to render.
Easiest way to do that, is not to call a server through an ajax, but instead to create a new script tag on the page with the url pointing to a RESTful web-service that would output pure JavaScript (not JSON). That way your output will be evaluated by the browser directly without the use of eval.
To expand a little on my answer:
To get around the problems of running script in the global context you could do some tricks. For example, when you are adding script tag to the head, you can bind onload event (or rather fake onload event, since IE doesn't support onload on the script tag) to it, and if your response from the server will be always wrapped in the the function with a known name, you could apply that function from within your object. Example code below (this is just an example though):
function test ()
{
this.init = function ()
{
var script = document.createElement("script");
script.type = "text/javascript";
script.language = "javascript";
script.src = "test.js";
var me = this;
window.callMe = function () { me.scriptReady(me); };
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
};
this.scriptReady = function (object)
{
serverResponse.call(object);
};
this.name = "From inside the object";
this.init();
}
var t=new test();
The server response should look something like this:
function serverResponse()
{
alert(this.name);
}
window.callMe();
In this case, everything inside serverResponse() will use your object as "this". Now if you modify your server response in this way:
function serverResponse()
{
this.serverJSONString = { "testVar1": "1", "testVar2": 2 };
function Test()
{
alert("From the server");
}
Test();
}
window.callMe();
You can have multiple things being returned from the server and with just one response. If you don't like just setting variables, then create a function in your main object to handle JSON string that you can supply by calling this function from your response.
As you can see, it's all doable, it really doesn't look pretty, but then again, what you are trying to do is not pretty to begin with.
P.S. Just inserting a string inside tag will not work for IE, it will not allow you to do that. If you don't have to support IE, then you could get away with just inserting server response inside a newly created script tag and be done with it.
P.P.S. Please don't use this code as is, cause I didn't spend too much time writting it. It's ugly as hell, but was just ment as an example:-)
No, you can't do this by definition, because JavaScript functions are not valid JSON. See the spec here:
http://www.json.org/
If you're returning a string, then that's what it is: just a string. You can't evaluate it without eval. You can call whatever else you're returning whatever you want, but please don't call it JSON.
Here's an example of how I think this could work.
The json object represents what is returned from the server. The c and d properties contain function names as strings. If those functions are properties of some other object which exists in your page, then you should be able to call them using the object["property"] accessor.
See it working on jsFiddle: http://jsfiddle.net/WUY4n/1/
// This function is a child of the window object
window.winScopedFunction = function() {
alert("ROCK THE WIN");
}
// This function is a child of another object
var myObject = {
myFunction : function() {
alert("ROCK ON");
}
};
// pretend that this json object was the result of an ajax call.
var jsonResultFromServer= {
a : 1,
b : 2,
c : "myFunction",
d : "winScopedFunction"
};
// you can call the local functions like so
myObject[jsonResultFromServer.c]();
window[jsonResultFromServer.d]();
Yes, there's a way, but it has the exact same disadvantages as eval.
You can use the Function constructor to create a new function, and then call it. For example:
new Function(code)();
http://code.google.com/p/json-sans-eval/ is a fast JSON parser that does not use eval, and JSON.parse is becoming increasing widely available in new browsers. Both are excellent alternatives to eval for parsing JSON.
You can use the trick that Google does with Google Charts.
<html>
<head>
<script>
function onWorkDone(data) {
console.log(data);
}
</script>
<script src="callback.js"></script>
</head>
</html>
Then your callback.js is:
function doWork(callback) {
callback({result: 'foo'});
}
doWork(onWorkDone);
Basically, your script will call onWorkDone when the doWork completed. You can see a working example here:
http://jsfiddle.net/ea9Gc/
Do you have some example cases? Some things I can think of is you that you can just have a regular function inside your js file, and your server will return some parameters for your function to execute. You can even specify what function to use! (Isn't that amazing?)
// your js file
var some_namespace = {
some_function : function(a, b){
// stuff
}
}
// your server output
{
some_other_data: "123",
execute: {
func: "some_namespace.some_function",
params: [1, 2]
}
}
// your ajax callback
function(r){
window[r.execute.func].apply(this, r.execute.params);
}
The reasons of not using eval
Well, you already said it yourself. Don't use eval. But you have a wrong picture regarding why.
It is not that eval is evil. You are getting the reason wrong. Performance considerations aside, using eval this way allows a sloppy programmer to execute code passed from server on the client. Notice the "passed from server" part.
Why never execute code passed from server
Why don't you want to execute code passed from the server (incidentally that's what you're planning to do)?
When a browser executes a script on a web page, as long as the web site is valid -- i.e. really yours, and not a malware site pretending to be yours trying to trick your users -- you can be reasonably sure that every bit of code the browser is running is written by yourself.
Hacker's heaven -- script injection attacks
Now, if you are passing data from the server to your web application, and that data contains executable functions, you're asking for trouble. In the long, twisted journey of that data going from your server to your client's browser, it goes through the wild west called the Internet, perhaps through multiple layers of proxies and filters and converters, most of which you do not control.
Now, if a hacker is hiding somewhere in the middle, takes your data from the server, modify the code to those functions to something really bad, and sends it away to your client, then your client browser takes the data and executes the code. Voila! Bad things happen. The worse is: you (at the server side) will never know that your clients are hacked.
This is called a "script injection attack" and is a serious sercurity risk.
Therefore, the rule is: Never execute functions returned from a server.
Only pass data from server
If you only accept data from a server, the most that can happen whan a hacker tempers with it is that your client will see strange data coming back, and hopefully your scripts will filter them out or handle them as incorrect data. Your client's browser will not be running any arbitrary code written by the hacker with glee.
In your client-side script, of course you're sticking to the Golden Rule: Do not trust ANY data coming through the Internet. Therefore you'd already be type-check and validating the JSON data before using it, and disallowing anything that looks suspicious.
Don't do it -- pass functions from server and execute on client
So, to make a long story short: DON'T DO IT.
Think of another way to specify pluggable functionalities on the browser -- there are multiple methods.
I've had this same question, and I fixed it this way:
File: functions.js.php?f=1,3
$functions=array(
'showMessage' => 'function(msg){ alert(msg); }',
'confirmAction' => 'function(action){
return confirm("Are you sure you want to "+action+"?");
}',
'getName' => 'function getName(){
return prompt("What is your name?");
}'
);
$queried = explode($_REQUEST['f']);
echo 'var FuncUtils = {'; // begin javascript object
$counter=1;
foreach($functions as $name=>$function){
if(in_array($counter, $queried))
echo '"'.$name.'":,'.$function.',';
$counter++;
}
echo '"dummy":null };'; // end javascript object
File: data5.json
{
"action" : ['confirmAction','exit']
}
File: test.js
$(document).ready(function(){
$.getScript('functions.js.php?f=1,3');
});
function onBeforeExit(){
$.getJSON('data5.json', function(data) {
var func = data.action.shift();
FuncUtils[func].apply(null, data.action);
});
}