silverlight with javascript - javascript

when i m trying to invoke javascript function which is present in my default.aspx page, it is showing some error --> Failed to Invoke: TalkToJavaScript.
coding in my silverlight page is--
public MainPage()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("Page", this);
HtmlPage.Window.Invoke("TalkToJavaScript", "Hello from Silverlight");
}
[ScriptableMember]
public void UpdateText(string result)
{
myTextbox.Text = result;
}

I would consider using this approach:-
public MainPage()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("Page", this);
Loaded += (s, args) => {
HtmlPage.Window.Invoke("TalkToJavaScript", "Hello from Silverlight");
};
}
I'm not sure why but I'd be uncomfortable calling back into Javascript from a constructor that I know is running in response to an Application_Startup. I'm either being irrational or this is the cause of your problem. Of course currently you aren't showing us the Javascript so you could simply have that messed up.

Related

How to call Javascript from #JavascriptInterface method in webView, Android?

Here is my HTML page codes:
<script>
function native_callback() {
alert("Test")
}
</script>
<button onclick='native.appVersion()'>appVersion</button>
As you can see, there is only one button, and when I click the button, it will call the #JavascriptInterface method appVersion(). What I want to do is to call the javascript function native_callback() in the appVersion() method. Unfortunately, I will catch a java exception.
And Here is part of my java source codes of WebView class:
... // some other codes that not related
getSettings().setJavaScriptEnabled(true);
addJavascriptInterface(new InJavaScriptLocalObj(), "native");
... // some other codes that not related
final class InJavaScriptLocalObj {
#JavascriptInterface
public void appVersion() {
Log.i("JsInterface","Called!")
loadUrl("javascript:native_callback()");
}
}
And, I can catch the exception from web page :
Uncaught Error: Java exception was raised during method invocation -- From line 6 of http://my web page url
Line 6 is <button onclick='native.appVersion()'>appVersion</button>.
BTW, the cods Log.i("JsInterface","Called!") has been called, I can see the log.
What should I do ?
Solution
Actually, it's must be called in another thread but same as your WebView object.
Here is my codes:
web_view.post(new Runnable() {
#Override
public void run() {
web_view.loadUrl("javascript:native_callback()");
}
});
How about using handler ?
I checked it works well in my project.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
loadUrl("javascript:native_callback()");
}
}, 0);

Understanding Android webview javascript interface

I have created an android WebView, and injected javascript interface using addJavascriptInterface(mObject, "jsinterface"). It works fine until I create an object with same name (jsinterface) in JavaScript using the new operator.
My Java Code:
WebView mWebView = findViewById(R.id.myWebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new MyWebChromeClient((Activity)mContext));
mWebView.addJavascriptInterface(new testClass(), "jsinterface");
mWebView.loadUrl("UrlToLoad");
testClass.java
public class testClass{
public testClass() {
}
#JavascriptInterface
public String testNativeMethod() {
return "Java method called!!";
}
}
My Java Script Code
test.js
function test(msg){
this.message = msg;
this.testJSMethod = function(){
return this.message;
}
}
alert(jsinterface.testNativeMethod()); // prints Java method called!!
jsinterface= new test("JS method called...");
alert(jsinterface.testJSMethod()); // prints JS method called...
alert(jsinterface.testNativeMethod()); // errors "NPMethod called on non- NPObject"
Problem:
Is this possible for a javascript object to have access to both , i.e javascript methods and native JAVA methods(exposed to it via javascriptinterface) ? Is there any possibility of setting any property to webview OR executing any JS script to get this done?
Think about document in javascript. When you are in a web browser, this is a global object that you have access to at any point. If you make your own new var called document, you are going to have problems accessing the global document.
When you execute this line:
mWebView.addJavascriptInterface(new testClass(), "jsinterface");
you are adding a global object called jsinterface. This is the same situation as document. If you create a var with the same name, it will overwrite the existing global reference.
Once you add a javascript interface to the WebView, you don't need to create a new reference to the interface. addJavascriptInterface has already done that for you.
TRY
You may try to make another object, which will retranslate calls to javascript interface.Implement onPageStarted method in WebViewClient , and inject javascript in onPageStarted method, in the following way.
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted (WebView view, String url, Bitmap favicon){
String jsScript= "javascript:var functions_array = ['testNativeMethod'];";
jsScript+="var jsinterface = {};"
jsScript+="functions_array.map(function(id){"
jsScript+="jsinterface[id]= function() {"
jsScript+="try{return temp_obj[id].apply(temp_obj, arguments);}"
jsScript+="catch(e) { console.log('ERROR: ' + e + ', method ' + id);"
jsScript+="return false;}}})"
view.loadUrl(jsScript);
}
});
Hope this helps :-)

GWT + SmartGWT + Javascript: external script integration

I am building a web application using GWT and SMartGWT and I need to integrate an external script for a Photo Gallery: http://slideshow.triptracker.net/.
My current attempt is:
ScriptInjector.fromUrl("http://slideshow.triptracker.net/slide.js").setCallback(
new Callback<Void, Exception>() {
public void onFailure(Exception reason) {
Window.alert("Script load failed.");
}
public void onSuccess(Void result) {
Window.alert("Script load success.");
}
}).inject();
Afterwards, I call this method:
Code:
native static void example(String p) /*-{
$wnd.viewer = new $wnd.PhotoViewer();
$wnd.viewer.add(p)
$wnd.viewer.show(0);
}-*/;
This does not give any error, but the photogallery appears BEHIND my Entry Point Layout, so it's not possible to use it.
So, I am trying to find a workaround and I would like to refer to the main layout from Javasript, to run the script on that. Is this possible? I've tried with
foo.getElement().getId();
but it returns me something like
isc_VLayout_0_wrapper
However, Javascript doesn't like it.
Then I tried
foo.getDOM.getId();
isc_1
But the result doesn't change.
Can someone help me fix this issue?
Thank You.
I think here are two things, that are possibly wrong:
You have an onSuccess() callback you can call the jsni call from within.
//1
ScriptInjector.fromUrl("http://slideshow.triptracker.net/slide.js").setCallback(
new Callback<Void, Exception>() {
public void onFailure(Exception reason) {
//3a
}
public void onSuccess(Void result) {
example("works");
//3b
}
}).inject();
//2
example("not loaded");
You may also try to call .setWindow(ScriptInjector.TOP_WINDOW) before calling .inject()

How to call javascript method from android

Hi In my android phonegap app i need to call the javascript method from android code (DroidGap).I have tried the sample code.
Here is my code:
super.loadUrl("file:///android_asset/www/index.html");
super.loadUrl("javascript:onload()");
When i use super.loadUrl("javascript:alert('hai')"); i am getting this alert.But when i use the method "onload" i am getting the error.
Here is my error in logcat:
Uncaught TypeError: Property 'onload' of object [object DOMWindow] is not a function at null:1
Here is my script in index.html:
<script type="text/javascript">
function onload()
{
alert("hai");
}
</script>
I dont know where i am wrong.Please guide me.Thanks in Advance.
Try this one and add this line also
super.setWebChromeClient(new WebChromeClient());
super.loadUrl("file:///android_asset/www/index.html");
After this line call like this onPageFinished
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() {alert("hai") }
);
}
});
Android can only call the javascript method if an html page is currently loaded in webView
first call
webview.loadUrl("Your html page url");
then call
webView.loadUrl("javascript:hello()");
Try to handle the alert function in the java file, like this :
mWebView.setWebChromeClient(new MyWebChromeClient());
final class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view,String url,
String message,JsResult result) {
new AlertDialog.Builder(MainActivity.this).
setTitle("Alert").setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
}).create().show();
result.confirm();
return super.onJsConfirm(view,url,message, result);
}
}
I had the same problem when I moved the target javascript function from the main page to an separate .js file. For some reason, the loadUrl() function can't find externally-loaded functions - only the ones in the main page. Once I moved the function back, it immediately started working.
Go figure.

How to handle Javascript events via WebBrowser control for WinForms

I have read WebBrowser Control from .Net — How to Inject Javascript, Is it possible to call Javascript method from C# winforms and many others. Those examples were returns function value or alert window (synchronous calls). I have to get result from event handler (async call):
<script type="text/javascript">
window.onload = function() {
var o = new M.Build(document.getElementById("ZID"));
M.Events.observe(o, o.Events.Success, function() {
// I have to get some value!!
});
M.Events.observe(o, o.Events.Fault, function() {
// I have to get some value!!
});
}
</script>
Calling C# from JavaScript
Simply put, you can expose a C# object
to the WebBrowser that the JavaScript
can call directly The WebBrowser
class exposes a property called
ObjectForScripting that can be set by
your application and becomes the
window.external object within
JavaScript. The object must have the
ComVisibleAttribute set true
C#:
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class ScriptInterface
{
public void callMe()
{
… // Do something interesting
}
}
webBrowser1.ObjectForScripting = new ScriptInterface();
Javascript:
window.external.callMe();
Calling JavaScript in a WebBrowser control from C#
This is code I have. In the DocumentCompleted event ('cause I'm getting a page from online)
var wb = (WebBrowser)sender
//Lots of other stuff
object obj = wb.Document.InvokeScript("MyFunctionName");
Create a function that returns whatever value you need and invoke away.
You can also inject a script into the page
string js = "function MyFunctionName(){alert('Yea!');}";
HtmlElement el = wb.Document.CreateElement("script");
IHTMLScriptElement element2 = (IHTMLScriptElement)el.DomElement;
element2.text = js;
head.AppendChild(el);
which can then be invoked. That's what I've done.
If your webBrowser control is in a form, you can do the following:
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1
{
public Form1()
{
InitializeComponent();
webBrowser1.ObjectForScripting = this;
}
public void CallMe()
{
//.... this method can be called in javascript via window.external.CallMe();
}
}

Categories