I came across some interesting behaviour of the javascript code on my XPages
//'rdoGeschlecht1' is present on page Basis (no problems there),
//but not on page 'Stufe1'.
var level = "Stufe1";
if(level == "Basis")
{
alert("1");
// var rdoGeschlecht1 = '#{javascript:getClientId("rdoGeschlecht1")}';
}
else if(level == "Stufe1")
{
alert("2");
}
The code above always ends in an error when executed on a page where the element is not present - "Ungültiger Komponentenname rdoGeschlecht1 kann in getClientId nicht aufgelöst werden." - it seems to me that Notes tries to resolve the object ID even if the line is not used in the actual execution and even when uncommented.
I have found a quick&dirty workaround of course, but I am surely not the first one to stumble upon this behaviour and I would really be interested in how experienced XPages programmers would be going about this?
The problem is you're commenting out the client-side JavaScript which is going to be run on the browser. But the server-side JavaScript code within #{javascript: (which needs to run on the server) is not commented out.
Perhaps it will help to explain what happens you put SSJS or EL in a string property or, in this case, a script block. Because the key is that the CSJS is not parsed on the server, it's just passed as a string to the browser.
The parser reads the string and looks for #{javascript: which tells it that the following code up to the closing } needs to be passed to the SSJS parser and the result added to the string that gets written to the browser. Any lines within that SSJS block that begin "//" will get omitted. But the parser will not take into account anything outside the #{javascript: because that is just text being passed to the browser. It is the browser that interprets the whole thing as client-side JavaScript.
Hopefully that clarified why it's working the way it is.
If you want to comment out a line in a script block that includes SSJS and you want to prevent the SSJS from running, you'll need to comment out the CSJS (so the browser doesn't run it) and the SSJS (so the server doesn't run it).
Related
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/
I'd like to write a test case (using Selenium, but not the point of this question) to validate that my web application has no script errors\warnings or unhanded exceptions at certain points in time (like after initializing a major library).
This information can easily be seen in the debug consoles of most browsers. Is it possible to execute a javascript statement to get this information programatically?
It's okay if it's different for each browser, I can deal with that.
not so far read about your issue (as far as I understood your problem) here
The idea be the following:
I found, however, that I was often getting JavaScript errors when the page first loaded (because I was working on the JS and was introducing errors), so I was looking for a quick way to add an assert to my test to check whether any JS errors occurred. After some Googling I came to the conclusion that there is nothing built into Selenium to support this, but there are a number of hacks that can be used to accomplish it. I'm going to describe one of them here. Let me state again, for the record, that this is pretty hacky. I'd love to hear from others who may have better solutions.
I simply add a script to my page that will catch any JS errors by intercepting the window.onerror event:
<script type="text/javascript">
window.onerror=function(msg){
$("body").attr("JSError",msg);
}
</script>
This will cause an attribute called JSError with a value corresponding to the JavaScript error message to be added to the body tag of my document if a JavaScript error occurs. Note that I'm using jQuery to do this, so this specific example won't work if jQuery fails to load. Then, in my Selenium test, I just use the command assertElementNotPresent with a target of //body[#JSError]. Now, if any JavaScript errors occur on the page my test will fail and I'll know I have to address them first. If, for some strange reason, I want to check for a particular JavaScript error, I could use the assertElementPresent command with a target of //body[#JSError='the error message'].
Hope this fresh idea helps you :)
try {
//code
} catch(exception) {
//send ajax request: exception.message, exception.stack, etc.
}
More info - MDN Documentation
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 have an ASP.NET MVC project that uses some simple AJAX functionality through jQuery's $.get method like so:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
});
The amount of content is relatively low here -- usually a single div with a short blurb of text. Sometimes, however, I am also injecting some javascript into the page. At some point when I dynamically include script into content that was itself dynamically added to the page, the script still runs, but it ceases to be available to the debugger. In VS2008, any breakpoints are ignored, and when I use the "debugger" statement, I get a messagebox saying that "no source code is available at this location." This fails both for the VS2008 debugger and the Firebug debugger in Firefox. I have tried both including the script inline in my dynamic content and also referencing a separate js file from this dynamic content -- both ways seemed to result in script that's unavailable to the debugger.
So, my question is twofold:
Is there any way to help the debugger recognize the existence of this script?
If not, what's the best way to include scripts that are used infrequently and in dynamically generated content in a way that is accessible to the debuggers?
I can not comment yet, but I can maybe help answer. As qwerty said, firefox console can be the way to go. I'd recommend going full bar and getting firebug. It hasn't ever missed code in my 3 years using it.
You could also change the way the injected javascript is added and see if that effects the debugger you're using. (I take it you're using Microsoft's IDE?).
In any case, I find the best way to inject javascript for IE is to put it as an appendChild in the head. In the case that isn't viable, the eval function (I hate using it as much as you do) can be used. Here is my AJAX IE fixer code I use. I use it for safari too since it has similar behavior. If you need that too just change the browser condition check (document.all for IE, Safari is navigator.userAgent.toLowerCase() == 'safari';).
function execajaxscripts(obj){
if(document.all){
var scripts = obj.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
eval(scripts[i].innerHTML);
}
}
}
I've never used jquery, I preferred prototype then dojo but... I take it that it would look something like this:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
execajaxscripts(result);
});
The one problem is, eval debug errors may not be caught since it creates another instance of the interpreter. But it is worth trying.. and otherwise. Use a different debugger :D
This might be a long shot, but I don't have access to IE right now to test.
Try naming the anonymous function, e.g.:
$.get(myUrl, null, function anon_temp1(result) {
$('#myselector').html(result);
});
I'm surprised firebug is not catching the 'debugger' statement. I've never had any problems no matter how complicated the JS including method was
If this is javascript embedded within dynmically generated HTML, I can see where that might be a problem since the debugger would not see it in the initial load. I am surprised that you could put it into a seperate .js file and the debugger still failed to see the function.
It seems you could define a function in a seperate static file, nominally "get_and_show" (or whatever, possibly nested in a namespace of sorts) with a parameter of myUrl, and then call the function from the HTML. Why won't that trip the breakpoint (did you try something like this -- the question is unclear as to whether the reference to the .js in the dynamic HTML was just a func call, or the actual script/load reference as well)? Be sure to first load the external script file from a "hard coded" reference in the HTML file? (view source on roboprogs.com/index.html -- loads .js files, then runs a text insertion func)
We use firebug for debug javascript, profile requests, throw logs, etc.
You can download from http://getfirebug.com/
If firebug don't show your javascript source, post some url to test your example case.
I hope I've been of any help!
If you add // # sourceURL=foo.js to the end of the script that you're injecting then it should show up in the list of scripts in firebug and webkit inspector.
jQuery could be patched to do this automatically, but the ticket was rejected.
Here's a related question: Is possible to debug dynamic loading JavaScript by some debugger like WebKit, FireBug or IE8 Developer Tool?