I'm wondering if it is possible to, in Java, detect whether or not an HTML file would open an alert dialog if opened in the browser. Preferably headlessly. For example, a file with the below contents were parsed, it would return true.
<html><script>alert("hey")</script></html>
and the below would return true also
<html><iframe src="javascript:alert(1)" onload="alert(2)"></iframe></html>
but the below would return false because it would not open an alert dialog if it were opened in the browser (because none of the code is syntactically correct, and the part that is isn't in a tag).
<html><script>alert;,(123w)</script>alert(1)</html>
I have thought of a way to approach this problem, but it is flawed. Basically, you see if the stringalert(1) is in the file, etc.
The problem with this is that it wouldn't work in cases where that code isn't inside of script tags or tags that make it execute. An example of where it wouldn't work is: The following would return true, even though it wouldn't actually open a popup <html>alert(1)</html>.
This isn't Android by the way. Appreciate your help!
You will need to not only verify if the Alert function is there but check if the JavaScript function would even run. An example of this is if there is a script with an Alert function inside a function that never runs. The Alert function would be there but it would never run. This would give a false positive. So the in the best case you should run the JavaScript in some way to validate the code and to see if the function would ever run.
As Louis pointed out in the comments Option 2 is better in this case as you will need to account for both the DOM and JavaScript's behaviour as both can change if the Alert function runs and how it runs.
Option 1 : Run the JavaScript with Script Engine
You would need some way of separating the HTML from the JavaScript but once you have that you can do this method.
You can run the JavaScript in Java using ScriptEngine. https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/api.html
If you read the API there is a way to create variables and communicate between your Java Program and the JavaScript you are Running.
To capture the context of the Alert you can create a custom JavaScript function that overwrites the Alert function. Inside this custom function you can send the arguments of the function back to your Java Program.
Option 2 : Headless Browser
You can also try to use a headless browser like JBrowserDriver and as you can see you have an Alert interface with getText as a function. For async issue the headless browser has a default amount of time for waiting for the script to complete. If this default amount is not enough you can use the setScriptTimeout to handle it.
http://machinepublishers.github.io/jBrowserDriver/
Related
I have written javascript that I am currently excecuting in the devtools of chrome (the console section). Is there any way to do that in javascript without me having to open the page, open the console, type it in, etc. I would be doing this from an external page. If this is confusing here is an example:
mypage.com
<script>
function myFunc(){return document.getElementById("hi")};
</script>
targetpage.com
<p id="hi">Hello world</p>
In this case, how can I run myFunc on targetpage.com from mypage.com?
Web browsers (by design) explicitly prohibit what you are trying to achieve. The JavaScript can only run on a page that originated from the same server.
The only way to "run" the code from a different source is via eval()
The way eval() works is you provide is with a JavaScript "text" that it will dynamically execute.
As mentioned in the comments - eval() is very evil.
eval() executes code provided as a text. For instance:
var code = "var i = 10; alert(i);";
eval(code);
The above lines will pop an alert window displaying "10".
The main point of the answer is: you cannot do what you are hoping to achieve.
I'm experimenting with a simple Javascript debugger for a WebView. I'd like to debug/control/inspect how some Javascript code is being executed inside my WebView.
I haven't found any solution other than using the WebChromeClient to receive the console messages.
Since I have access to the Javascript code I can add instrumentation code: a console.log call before each line, with a special message (e.g. "debugging line 3") that tells which lines have been executed.
It's quite rudimentary so I wonder if there's any better solution. It would be great if I could use the debugger statement to really control execution flow.
This is what I have been doing if I want to console.log() anything directly on the mobile browser so that debugging can be done on the actual device and not in emulator or similar...
I made JS debugger plugin and here is what it have:
it creates an absolutely positioned HTML element that is placed on top of the content and is semi transparent.
I made the JS logic that actually simulates what console.log() does and print out all desired information in mentioned HTML element
once plugin was done I simply used MoibileDebugger.log('what ever'); instead of console.log('what ever');
My code is still not published publicly but will do that soon, so that anyone can benefit from using it...
In any case this plugin can be made very quickly by anyone who is good in JS.
I'm trying to create a Firefox extension that fires my Javascript code before any of the current page's Javascript is fired. My Javascript code will basically control whether or not the page's Javascript code can be executed or denied.
I first started out by trying to follow this answer, but I couldn't really figure out how to get it to work and realized I was relying on onDOMContentLoaded, which loads after the Javascript has already executed.
I then turned my attention toward XPCOM, but once again didn't really understand what the Firefox tutorials were telling me.
I've recently been trying to make an extension through Firebug, but I seem to hit the same problem... only having access to the Javascript after it's been parsed/executed. Here's the resulting code that I wrote. I think if I could access the file's objects in the onExamineResponse event, my problem could be solved, but I don't know how to do that... I'm talking about this code:
BeepbopListener.prototype = {
onRequest: function(context, file) {
...
},
onExamineResponse: function(context, file) {
FBTrace.sysout("onexamineresponse " + file); // this returns something like
// '[xpconnect wrapped (nsISupports, nsIHttpChannel, nsIRequest, nsIUploadChannel, nsITraceableChannel, nsIHttpChannelInternal)]'
// but I don't know how to access those elements...
var pattern = /\.js$/;
if (pattern.test(file.href) && FBTrace.DBG_BEEPBOP) {
FBTrace.sysout("ONEXAMINE DOESN'T EVEN GET IN THIS IF SO YOU WON'T SEE THIS");
}
},
...
};
So my question is... is there a tutorial out there that shows me how I can get access to all Javascript code on a page before it's executed? Also, if anyone has any helpful insight, I'd love to hear it. Oh, and if y'all need more code from me, just let me know, and I'll post it.
You can access a new document before any JavaScript code runs by listening to the content-document-global-created observer notification. However, the document will be empty at this point and JavaScript code will run as soon as the parser adds a <script> tag - you cannot really prevent it. Here are the options to control script execution that I am aware of.
1) Disable all JavaScript for a window using nsIDocShell.allowJavascript:
wnd.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShell)
.allowJavascript = false;
This is an all or nothing approach. Note that JavaScript stays disabled even when a new document loads into the same frame.
2) Implement the nsIContentPolicy interface in an XPCOM component and register it in the content-policy category (via nsICategoryManager). Your shouldLoad() function will be able to block scripts selectively - but it will only called for external scripts (meaning <script src="...">), not for inline scripts on the page.
3) Use JavaScript debugger service to intercept script execution. You could use jsdIDebuggerService.interruptHook to step through JavaScript execution and abort the script whenever you like. But that would slow down JavaScript execution very significantly of course. At the very least you should use jsdIDebuggerService.addFilter() to restrict it to a particular document, otherwise you will slow down the entire browser (including browser UI).
I'm trying to create a Firefox extension that fires my Javascript code before any of the current page's Javascript is fired. My Javascript code will basically control whether or not the page's Javascript code can be executed or denied.
Start by completely preventing the document from getting parsed altogether then on the side, fetch the same document, do any processing on this document and then inject the resulting document in the page. Here is how I currently do just that https://stackoverflow.com/a/36097573/6085033
I need to build a web application that allow user to input javascript code and the code is then dynamically executed and somehow show the result at the same page. The flow would be something like this:
In the webpage, there area a series of textarea, and under each of these textareas, there is a result div element (or whatever element span, p, doesn't matter). User will input javascript code inside the textareas. He should be able to enter whatever javascript code he want, but at the end he will call a custom function like
my_application_output(some_variables_computed_from_previous_code_execution)
and then something will be displayed on the result div. A simple example will be:
if he input the following text in the textarea:
var a = 0;
a++;
my_application_output(a);
and then execute the code, the result div element below the textarea will have a inner html content of "1"
I don't have much idea how to get started, like what technologies or system architecture should I go for. so would like to ask for some pointers here. I have thought about two options (not sure whether they are good enough)
Use JavaScript eval() function. so I just execute the code from the textarea directly on the client side.
Implement a backend service using an engine like V8. So I do a ajax call to backend with the code content, and then the codes are executed from backend, and result is returned. I then put the result in the result div accordingly.
Personally, I'd like to go for 1) because eval() seems to be a easier solution. However, I'm not sure whether there is any limitation about this function or whether it can achieve what I want to do. Otherwise, if I have to go for the second option. Anyone can propose an architecture for that?
Not only is option 1 easier, it is also the safer choice.
Why? Everyone who has Firebug installed in Firefox (or just has the Chrome Dev tools open) already has what you're asking for, though perhaps in not as noob-friendly a fashion. The code they write is sandboxed to the browser they're using and nothing more.
With option 2, you're going to execute arbitrary untrusted code on the server. Suppose they realize that you're using Node.js (the most likely choice here) and then run a fork-bomb on your server:
require('child_process').exec(':(){:|:&};:', function() { console.log('This will never run') });
Let alone something more nefarious.
Remember that REPL stands for Read-Eval-Print-Loop, and is what dynamic languages since Lisp have used to help programmers understand their languages. Eval is perfectly fine if the only person a newbie can hurt is themselves.
I am am running some selenium tests(ruby) on my web page and as i enter an invalid characters in to a text box i have the JavaScript throw a alert like so
if(isNaN($(this).val()) || Number($(this).val().valueOf() <=0)){
alert("Please Enter A Number");
}
how can i handle this alert when its made and close the pop up?
i tried to use the wait_for_pop_up() and close() but i think that's only for browser pop up's and not JavaScript alerts.
any ideas?
thanks
The documentation isn't of much help but the Java Docs for Selenium RC seem to show that a getAlert() does exist here. Also this site lists these functions as well:
Processing with Selenium The following commands are available within Selenium for processing Alerts:
getAlert()
assertAlert() assertAlertNotPresent()
assertAlertPresent() storeAlert()
storeAlertPresent() verifyAlert()
verifyAlertNotPresent()
verifyAlertPresent() waitForAlert()
waitForAlertNotPresent()
waitForAlertPresent()
The …AlertPresent() and …AlertNotPresent() functions check for the existence or not of an alert – regardless of it’s content. The …Alert() functions allow the caller to specify a pattern which should be matched. The getAlert() method also exists in Selenium RC, and returns the text from the previous Alert displayed. Similar functions are also available for Confirmations
Selenium intercepts all JavaScript alert() calls (as well as confirm() and prompt()) and handles them itself. You can tell it what you want it to do, and you can find out what happened (excepting during onLoad, as Zugwalt says). You can call isAlertPresent() to check whether an alert was generated or not, and getAlert() to retrieve the text of it. Selenium will even queue them up for you, in case there is more than one (they're retrieved in order). If an alert is generated and you don't call getAlert() to retrieve it, the next Selenium operation will throw an exception. And if you call it when there isn't one, you'll get an exception.
For example (untested, and in C#, but you should get the point):
selenium.GetEval("window.alert('Hi, mom!'); window.alert('Bye, dad!')");
Assert.AreEqual("Hi, mom!", selenium.GetAlert());
Assert.AreEqual("Bye, dad!", selenium.GetAlert());
Assert.IsFalse(selenium.isAlertPresent());