javascript and loadUrl error - javascript

i know that to run a javascript function in webview we need to load it in loadUrl(). In my program everything works fine javascript gets called when i use it in loadUrl, but instead of running javascript on the same page, loadUrl("javascript:function()") vanishes my previous page and run this javascript "function()" in a totally new blank page..
for eg. i tried to fill a form automatically using command:
view.loadUrl("javascript:document.getElementById('password').value = 'my_passoword'");
what happens is, the page which consists of ID-'password' vanishes and a new blank page generates consisting of 'my_password' only
where is the problem?

Using loadUrl to run javascript loads different page
anonymous self-invoking function works fine.. i.e.
view.loadUrl("javascript:(function(){document.getElementById('password').value = 'sb14november';})()");
and as a loop around i think Bojan Kseneman answer will work too..
thanks to all!! :)

EDIT: This library is only for evaluating JavaScript and it created a new WebView instead of using an existing one :/
You can also try js evaluator library
jsEvaluator.evaluate("put your JavaScript code", new JsCallback() {
#Override
public void onResult(final String result) {
// you get the result here (optional)
}
});

Related

Javascript "value=..." returns blank page

Follow the following steps.
Steps 1:
Go to google.
Open the javascript console.
Enter the command: document.all.q.value = "hello"
As expected the element with a name of "q" (the search field) is set to "hello").
Steps 2:
Go to google.
In the address bar type javascript: document.all.q.value = "hello!"
Press Enter
If your browser is either Internet Explorer, or Google Chrome, the javascript will have replaced the google website with an entirely blank page, with the exception of the word "Hello".
Finally
Now that you've bugged out your browser, go back to Google.com and repeat Steps 1. You should receive an error message "Uncaught ReferenceError: document is not defined (...) VM83:1
Question:
Am I doing something wrong? And is there another method which works, while still using the address bar for JS input?
The purpose of a javascript: scheme URL is to generate a new page using JavaScript. Modifying the existing page with it is something of a hack.
document.all.q.value = "hello!"; evalues as "hello!", so when you visit that URL, a new HTML document consisting solely of the text hello! is generated and loaded in place of the existing page.
To avoid this: Make sure the JS does not return a string. You can do this by using void.
javascript:void(document.all.q.value = "hello!");
When messing around with javascript: in the adressbar some (if not the most) browsers handle it as a new page, so you have to add a window.history.back(); at the end
javascript: document.all.q.value = "hello!"; window.history.back();

Javascript bookmarklet fails on certain sites, creates ghostly new <html> page

I noticed that my Javascript bookmarklet was failing on certain sites like Google Reader and Google search results pages (and randomly on some non-Google sites). Looking at the console, I could see that, for these pages, clicking the bookmarklet did not append elements to the head/body like it normally did, but created a new document that looked like this:
<html>
<head></head>
<body></body>
</html>
Even when I reduced my bookmarklet to javascript:alert(window.location.href); it would create this blank page and run the bookmarklet therein, so that the alert showed about:blank. On most sites, this blank page is not created and the correct location is shown.
Can someone explain this? Are these sites sandboxing externally run code as a safety measure?
UPDATE: I currently can't reproduce this on browsers other than Chrome 17.0.932.0 dev. Please let me know if anyone else can reproduce these results on Chrome or otherwise.
I think this is a bug in Google Chrome, I've filed it to their bug database: https://bugs.webkit.org/show_bug.cgi?id=72606
You need to ensure that the topmost code, i.e. the one right after javascript: does not return anything.
Usually this is done by wrapping everything in void():
javascript:void(alert(window.location.href));
It's very odd that it breaks with alert() though since the function itself doesn't return anything...
If a javascript: url returns a string it will be used to create a new document:
javascript:'foo bar baz';
This can be a tough issue to debug if you don't know to watch out for it. It can crop up if you use a function that returns a string or end your bookmarklet with a line that sets a string value:
javascript: a = prompt('foo bar baz'); b = a;
A simple solution is to use a closure:
javascript:(function(){ var a; a = prompt('foo bar baz'); window.b = a}());
An alternative is to end with void 0;
javascript: a = prompt('foo bar baz'); b = a; void 0;

Getting content out of WebView In a unit test Android, using java script

I have been able to get content out of WebView using javascript and loadUrl() method having specified an interface thats called from javascript string that is injected into WebView.The problem is that this only works for me when the loadUrl() method is present in onPageFinished() method in the WebView client. What I want to do is I want to get the content out of the WebView (with the content already loaded). The WebView is in an activity instrumentation test case and I can for instance use findAll() method and that works fine. For some reason I can not use loadUrl() and get the desired behaviour (which is injecting javascript and getting content out of the WebView with a help of an interface).
PLease help.
Thanks
Pawel
EDIT:
Just adding code to show what I am doing exactly:
Yes I understand that but my problem is that I am trying to do it within a test case this way:
public void testWebView() throws Exception {
solo.sleep(3000); // wait for views to load on the screen
WebView a=null;
ArrayList<View> views = solo.getCurrentViews(); // I am using solo object to get views for the screen currently loaded
for(View s:views)
{
if (s instanceof WebView)
{
a = (WebView)s; // this is where I get my WebView
}
}
Instrumentation inst = getInstrumentation();
inst.runOnMainSync(new Runnable()
{
public void run()
{
int d =a.findAll("something"); // this method runs fine on the object and i get the desired result
WebSettings settings = a.getSettings();
settings.setJavaScriptEnabled(true);
a.loadUrl("javascript:document.location = document.getElementById('google').getAttribute('href')"); // this javascript is never executed and that is my problem
}
});
}
You can inject javascript in a loaded page much the same way you can do it in desktop browsers - via inline javascript entered into navigation bar.
Bind some Java object so that it can be called from Javascript with WebView:
addJavascriptInterface(javaObjectExposed, "JSname")
Force execute javascript within an existing page by
WebView.loadUrl("javascript:window.JSname.passData("some data from page");");

How to received alert() action from javascript into Cocoa application via WebView

I was develop some Cocoa application with WebView. Now I can evaluate javascript to HTML file by using evaluateWebScript:
But I need to receive an alert() event from javascript to display in Cocoa's NSAlertSheet.
How to do with cocoa development ?
You need to set an object as the WebUIDelegate of the WebView (using the setUIDelegate: method) and in that object implement the ‑webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame: delegate method. This method will be called when a page loaded into the WebView calls the alert() JavaScript function.
In your implementation of the delegate method, you should display an alert. The alert should:
display the exact message string that is passed in to the method
indicate that the message comes from JavaScript
contain only one button, an OK button
Here is a basic example:
- (void)webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message
{
NSAlert* jsAlert = [NSAlert alertWithMessageText:#"JavaScript"
defaultButton:#"OK"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:#"%#", message];
[jsAlert beginSheetModalForWindow:sender.window modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
}
You can try to override JavaScript alert function on window. In your custom alert you can redirect to predefined url, e.g. app://alert/something%32is%32wrong. That kind of redirect can be handled by UIWebView through webView:shouldLoadRequest:.
PS: I didn't try it :)

Changing the Android Webview hash without reloading page

I'm got a custom webview setup which is working pretty well, but I'd like to be able to either:
1, change the url hash without the webview reloading the page (it would lose the state of my js app)
2, call some js that sits within my web page from within android. I can't change any JS within the site, unfortunately, so can't custom write any js to put on the site especially for the job, the only stuff I have control over is the Android app.
Can anyone think of a way of doing either of these?
Thanks in advance.
M
Or if you just want to change the hash, you can use:
view.loadUrl("javascript:location.hash=\"#" +fragment+"\"");
For #2, your Activity can invoke JavaScript methods. All you have to do is call the loadUrl method with the appropriate JavaScript call:
mWebView.loadUrl("javascript:wave()");
From:
http://developer.android.com/resources/articles/using-webviews.html
I know this question is old but this is what works for me in Android 4.4:
String fragment = "#test"
mWebView.evaluateJavascript("location.hash=\"" + fragment + "\";", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
// Yes, I like to log data :-)
Log.d("MyApp", "onReceiveValue(value): " + value);
}
});

Categories

Resources