How to debug JavaScript files which are loaded dynmically? - javascript

Currently the web application I am working on loads in a number of script files using jQuery.Load() when the document DOM is ready. However, if those script files have syntax errors, neither Firebug or IE Developer Tool can reliably shows the line with error or give some really huge line numbers.
How can I debug such scripts? Or should I load them via script tags until I have verified that they are bug free?

firebug plugin for mozilla has a inbuilt javascript debugging tool. Which can be used for the purpose mentioned

I had exactly the same problem with YUI3. I reverted back to the admittedly less cool but more stable approach of including the required files - YUI3 has a neat tool for giving you all those script tags - i don't know if it's the same for JQuery. Sorry that's probably not that helpful!

Load them in by dynamically adding a script tag for them (using the DOM), that should do the trick:
var newScript;
var loadFunc = function ()
{
alert("External Javascript File has been loaded");
};
newScript = document.createElement('script');
newScript.setAttribute('type','text/javascript');
newScript.setAttribute('src');
newScript.onreadystatechange = function() //IE triggers this event when the file is loaded
{
if (newScript.readyState == 'complete' || newScript.readyState == 'loaded')
loadFunc();
};
newScript.onload = loadFunc; //Other browsers trigger this one
document.getElementsByTagName('head')[0].appendChild(newScript);

Related

JavaScript is not function properly when set it locally

I want to import raphael-min.js for my jsp. I'm using
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script>
tag for importing of the script. But the I want to include this js locally because when rendering this script is blocked by the browser. I copy the code from the url above and save it as a js file. and include as this
<script src="${pageContext.request.contextPath}/resources/raphael/raphael-min.js"></script>.
But the problem is js is not function at all. Are there any method to download this and include in jsp file?
We may load js file adding script tag in DOM:
Try the below code:
var script = document.createElement('script');
script.src = PATH;
script.onload = function(){
FILE LOADED
};
document.head.appendChild(script);
It seems weird that a browser is blocking a cloudflare.com URL - are you using AdBlock or similar extensions? Try accessing the page through incognito or private browsing mode (assuming that the extension is disabled - the default - in that mode) for Chrome and Firefox respectively.
If you are seeing a particular error message, please post the error message - it will probably give clues as to why it is being blocked.
P.S: I would've posted a comment if my reputation allowed it. If you post clarifications, I can edit this answer accordingly.

How to disable facebook hotkeys with Chrome extension?

I have created a Chrome extension that uses the hotkeys [Alt]+[0...9] only to discover facebook uses the same hotkeys. Is there any way possible my extension could disable facebook's hotkeys so that mine fire alone? I'm fairly certain I have identified the code facebook uses to implement their [Alt]+[0...9] hotkeys:
document.documentElement.onkeydown=function(a){a=a||window.event;var b=a.target||a.srcElement;var c=a.keyCode==13&&!a.altKey&&!a.ctrlKey&&!a.metaKey&&!a.shiftKey&&CSS.hasClass...
This is in a script called from the head of the root document. I have tried the following to disable them:
//contents script:
$().ready( function() {
document.documentElement.onkeydown = '';
});
and even
$().ready( function() {
document.documentElement.onkeydown = function(e){};
});
I am guessing further that the reason neither of these attempts work is because although Chrome extension content scripts share a DOM with any webpage on which they run, perhaps they do not share coding environments? Any insight would be appreciated!
Chrome's Content scripts are executed in a Sandboxed environment [source]. There is no direct way to communicate with the global (window) object.
Another common pitfall is that the developer forgets how/when the script is injected.
By default, the script is injected at a point called "document_idle". At this point, the document is not busy (DOMContentLoaded has fired, window.onload may or may not have fired).
As a result, the functions in the script may be overwritten immediately after declaration.
To inject a small script, I recommend to add the code directly to the Content Script:
var actualCode = '/* Code here (see below for inspiration) */';
var script = document.createElement('script');
script.appendChild(document.createTextNode(actualCode));
(document.head || document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
If you want to make sure that the method is not going to be overwritten, you can use Object.defineProperty, to define an immutable property:
Object.defineProperty(document.documentElement, 'onkeydown', {
value: function() {},
writable: false, /* Cannot be overwritten, default false */
configurable: false, /* Cannot be deleted, or modified */
enumerable: true /* Does not really matter. If true, it's visible in
a for-loop. If false, it's not*/
});
The previously mentioned method is supported in Firefox 4+ and at least Chrome 5+. If you want to also support Firefox 2+ and Chrome 1+, you can play with the __defineSetter__, to prevent onkeydown from being defined:
document.documentElement.__defineSetter__('onkeydown', function(){});
Your intuition is correct, the JavaScript that runs from a content script as part of a Chrome Extension is run in a sandbox that does not have access to the JavaScript that is executed in the containing page.
Per the Chrome doc on Content Scripts:
However, content scripts have some limitations. They cannot:
* Use chrome.* APIs (except for parts of chrome.extension)
* Use variables or functions defined by their extension's pages
* Use variables or functions defined by web pages or by other content scripts
First off, I would recommend that you consider different shortcut keys. Overriding the functionality of existing shortcut keys for your own extension could provide a jarring user experience for someone that is expecting the Facebook shortcut key. Imagine if an extension overrode the ctrl-c and ctrl-p shortcuts that are a part of the desktop OS for copy and paste - I think you would have some upset users that would probably remove the thing that changed the behavior they learned prior.
However, if you are insistent, then here is a workaround to loading JavaScript that will execute in the context of the containing page:
Edit: Updated per comment to reference JS file in a plugin instead of one hosted on the web
First, you will need to create a JavaScript file in your chrome plugin: override-fb-hotkeys.js.
First, you will need to host a JavaScript file somewhere on the web that contains the script that you want to execute in the page, let us say you host it at: http://example.com/override-fb-hotkeys.js.
Then, from your content script, you can insert a script tag into the DOM that references your JavaScript file, something like this:
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("async", true);
script.setAttribute("src", chrome.extension.getURL("override-fb-hotkeys.js")); //Assuming your host supports both http and https
var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
head.insertBefore(script, head.firstChild)
The JavaScript will then be fetched and executed in the context of the containing page, not the sandboxed code from the Chrome plugin.
This is how you can do it using jQuery
Remove all shortcuts for any webpage:
$('[accessKey]').attr('accessKey','')

CKEditor variable is available in console, but not from a Chrome userscript?

I'm writing a Chrome userscript to locally auto-save content in a CKEditor. I'm using this CKEditor auto-save plugin as inspiration.
I have written a function that fires every half second (via an interval) to register the CKEditor event handler:
var intervalId = window.setInterval(function() {
if (CKEDITOR) {
window.clearInterval(intervalId);
CKEDITOR.plugins.add("user-script-auto-save", {
init : function(editor) {
editor.on('key', startTimer);
}
});
}
}, 500);
However, it never properly completes, and complains that "CKEDITOR is undefined" on the if (CKEDITOR) statement.
Meanwhile, if I drop into Chrome's console and type CKEDITOR, the console prints out the expected object.
What am I missing? The editor is embedded within an iframe; might that have an impact on scoping? Or am I fighting against Chrome's sandboxing here? And if so, is there some other way I can dig into CKEditor to pull out the content every second or something to do the auto-saves?
I have not yet tried the script in Firefox; that's next on my list.
Worth noting: I'm a long-time JavaScript novice. So I could easily be doing something dumb with scoping or something like that.
According to this little tutorial video on YouTube, all the 3 "devices" are separated from each other in order to prevent XSS attacks from the user script to the browser / website and vice versa. Although the user scripts / content scripts are running in the website's context, they are still kept separated from the actual website script context. You can easily acknowledge this by simply trying to access for example jQuery from a content script. Just as the CKEditor, it will not be available.
So what I've come up with in order to deal with this is using the content script to include external JavaScripts in the head tag. AFAIK, this is not possible for files directly in the extension's root directory, so I've taken a remote server to host my files.
I'm not sure if this is the best approach and I think it is an ugly bypass, possibly way to powerfull and disabled by the Chromium Project some time.
(Edited by OP, so I can select this answer and route karma appropriately)
This answer, combined with some of the suggestions and links in the comments, ended up getting me to where I needed to be.
I ended up with the following function:
var insertScriptIntoDocument = function(scriptUrl, doc) {
// inspired by http://blog.afterthedeadline.com/2010/05/14/how-to-jump-through-hoops-and-make-a-chrome-extension/
var scriptText = doc.createTextNode(
'(function(loc) { \
var embeddedScript = document.createElement("script"); \
embeddedScript.type = "text/javascript"; \
embeddedScript.src = loc; \
document.getElementsByTagName("head")[0].appendChild(embeddedScript); \
})("' + scriptUrl + '");');
var injectorElement = doc.createElement('script');
injectorElement.appendChild(scriptText);
doc.body.appendChild(injectorElement);
};
Usage looks like so:
var embeddedScriptUrl = chrome.extension.getURL("embedded-script.js");
insertScriptIntoDocument(embeddedScriptUrl, document);
For now, I'm executing this from within a Chrome extension, but I suspect that the pattern might work in a GreaseMonkey script deployed via the Chrome TamperMonkey extension provided that the URL of the script to be embedded was hosted somewhere reachable.
FTR, as it turns out, I did not actually need to get to the iframe -- the CKEDITOR variable was defined in the top-level document, but was simply not visible because of the rules of the Chrome sandbox

Creating a bookmarklet that doesn't get blocked

Goal: To create a bookmarklet that calls a remote javascript file that opens a popup window. The popup window is functionally similar to what Delicious's bookmarklet does.
Background: Currently, I'm using window.open within this javascript file, however the popup is getting blocked by pretty much every major browser.
The alternative solution to this is very similar to the way Delicious wrote their bookmarklet - calling window.open through a javascript query within the bookmarklet itself. However, I need the ability to modify the other contents of my javascript file in the future without requiring users to continually grab newest releases of the bookmarklet.
What I've determined to be happening: Since the window.open call is not occurring directly as a result of a click by the user, the browser feels this is something that should be blocked. Here's a source on this.
This is the tutorial I referenced most recently in creating the call to the remote js file.
Here is a basic example of what my code is doing; the window.open/popup portion is the only significant part I'm including as it's the only part I feel is causing the complication:
Example of the remote javascript file:
if (typeof jQuery == 'undefined') {
var jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.onload=runthis;
jQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
document.body.appendChild(jQ);
} else {
runthis();
}
function runthis() {
window.open('http://www.google.com/', 'a title',
'location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550');
}
I'd really appreciate any help as this has been stumping me for a while!
An approach that looks better and side-steps the blocking issue is to have the bookmarklet insert an iframe in the page the user is currently viewing. Ended up taking this approach back when I asked this question. Worked out fine.

Google Search API Inside Firefox Extension

I am developing a firefox extension and I need to include the Google Search API. But I am encountering an error in the google.load('search','1') line. Can anyone tell what the problem is
Thanks.
I have the same problem, but according to what I can see in Google's JS code, it tries to add variable 'google' to window, but the extension is loaded when there is no window yet! So there will be no global google variable and therefore an error occurs when you try to fire google.load().
I think the solution is to load the script dynamically. I have just found an existing addon for transliteration:
h t t p s : / / addons.mozilla.org/pl/firefox/addon/8960
Look how they have solved the problem:
onPageLoad: function(event) {
var doc = event.originalTarget;
var ele = doc.createElement('script');
ele.setAttribute('type', 'text/javascript');
ele.setAttribute('src', 'h t t p : / / www.google.com/jsapi?key=internal');
}
onPageLoad is loaded when DOMContentLoaded event occures, so when the whole tree of the page is loaded (it seems it's a DOM equivalent to onLoad)
(Forgive me inserting spaces in links, but otherwise I would not be permitted to post them :])
If you've gathered all the JavaScript files and are packaging them with your Firefox extension locally, and google's load function was designed for loading JavaScript from a server then your problem is that you can't use the load mechanism in that library. Instead use Components.utils.import or mozIJSSubScriptLoader depending on the version of Firefox you're targeting.
This might require editing, extending or overwriting the code in Google's library.

Categories

Resources