Having trouble overriding the document object in JavaScript - javascript

I'm having a spot of trouble overriding the document object for my JavaScript.
function myFunction(document) {
[code]
}
works fine. But
function myFunction(newDocument) {
document=newDocument
[code]
}
does not. So far I'm managing fine using functions with the former method, but I'd rather just override the document object once and forget about it. If anyone could show me the proper way to globally override the document object, I'd appreciate it.

I'm going to go out-on-a-limb and say this cannot be done, nor should it be done.
If you replace the current document object (that your script is running under) than wouldn't your script go out of scope/context?
I made a fiddle (http://jsfiddle.net/V3Rsh/) that suggests this cannot be done (at least in Firefox 20). If you look at the console it reports the same URL before and after the document assignment. But if you debug and put a breakpoint on the first console.log() and run the document = newDocument() line manually in the console you will see a document object created that has the 'about:blank" URL. But the subsequent call to console.log() does NOT reflect that.

Related

Inspecting console.log variables in Chrome

As a thought, i would like to know if is possible to inspect for log properties of any variable in the chrome or any other browsers within the console mode. As i already know that you can already inspect the DOM in inspector element and you can go through debugging mode also. I want to demonstrate my point and why i and most novice would benefit this.
So as you can see in the picture below:
So as you can see i am trying to access some element of Array[15] but in the end it always giving me undefined. It nice just to test out some code before recompiling it again which takes time. Plus sometime you don't always knows enough that the function you are calling in JS is compatible with what you trying to achieve.
Put your entire code inside:
$(document).ready (function (){
//Paste your code here
});
The whole point is you are trying to access an element in the DOM before it exists.
When your trying to access the class the item doesnot exist.
Alternative:
Move your script below the elements in the html.
This is a very generic solution I gave without seeing the code. Request you to post the code as well.
Hope it helps.
You need to add a debugger where you are outputting your array. It seems to me you are trying to access the variable after execution is over, so the variable value is lost, as it goes out of scope. When execution stops at the debugger, you can console.log your variable and properties. At that point the variable will be in scope.

why jQuery attr('href', '#') set an empty value rather than #

I'm using jQuery version 1.8.3
jQuery('#edit_param_apppmStyleImage').attr("href","#");
The HTML turns out with
<a id="edit_param_apppmStyleImage" href="">Edit</a>
It sets an empty value rather than "#". And it is 100% surely caused by my site's special script written by others.
Any specialist can provide some suggestions about what may cause such weird behavior? Btw, it sets other values like '##' normally.
It sets an empty value rather than "#". And it is 100% surely caused
by my site's special script written by others.
You did not provide any details regarding the special script running on your site. But I'd try running the script after everything (including images) is loaded. In that case, this is what comes to my mind;
The load event is sent to an element when it and all sub-elements have
been completely loaded.
Since it's a bit different than $(document).ready() function, it could make a difference if some other script is overriding your script's intended behaviour.
Try the following
jQuery(window).bind("load", function() {
jQuery('#edit_param_apppmStyleImage').attr("href","#");
});
What we're doing here is that we're delaying the execution of the script until the entire window is loaded. And since anything in $(document).ready() function executes before the code in $(window).load() function, we are reducing the chance of your script to be overridden.
Not sure that will work, but give it a try.
Replace attr() with prop():
jQuery('#edit_param_apppmStyleImage').prop("href","#");

Content Scripts: Page-worker - <body> element with 0 width

I want to automatically open a website and reveal details about the rendered DOM. For that purpose I use a page-worker (https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/page-worker). When in the content script I execute something like the following:
var body = document.getElementsByTagName("body")[0];
console.log(getComputedStyle(body).width);
console.log(body.getBoundingClientRect().width);
The output is "0" for both of the width values. The same also applies to other elements. Should I conclude that DOM elements are not rendered properly when using a page-worker? Is there a way to gain authentic data from that? Or is there any other proper way to get details about the rendered DOM that behave exactly like the website was opened in a web browser by hand? Because if I open the same website manually and execute the same commands, it reveals (correctly) the width of the window (1440), of course.
edit
I probably should have said that before, but:
It's not that gaining the values does not work at all. If I go deeper in the DOM structure, I get correct values. I only have problems with the root body element, I think. Weirdly enough if I execute the exact same commands on the firefox console, the return values are perfectly correct.
It's very interesting the way you do it.
You don't have to do getElementsByTagName to get the body element, its a property of the document object var body = document.body;
getComputedStyle is a function of the window object so that's why it works without you putting window. in front of it but still just want to let you know.
You dont do a getPropertyValue which is required for getComputedStyle, I just tried it without it and it worked but i never saw it used like that before so maybe that has something to do with it:
So doing this from bootstrap or from scratchpad window: gBrowser.contentWindow.getComputedStyle(gBrowser.contentDocument.body).getPropertyValue('width')
works for me.
From your content-script scope do:
window.getComputedStyle(document.body).getPropertyValue('width')
If it still doesn't work I would thinky maybe myabe maybe, thers a chance you might be executing the code to early.
Let me know how that works.

How can I access DOM objects in an external JavaScript file?

I'm using an external JavaScript file to access DOM objects with in my documents. The problem is that jQuery doesn't seem to have access if it's an externally loaded file. My code looks like:
<html>
<head>
</head>
<body>
<div id="domToChange" someAttribute="hi"></div>
<script src="officialJqueryLibrary"></script>
<script src="myJS.js"></script>
</body>
</html>
///////// myJS.js file
// Returns undefined
$('#domToChange').attr('someAttribute');
The DOM selector doesn't seem to find my div when the JavaScript file is loaded externally. However everything works when I place it inside the HTML document itself. How can I give DOM access to my JavaScript file?
You should wrap all your DOM related code into
$(function() {
//Code
});
Then the code gets executed when the DOM is fully loaded.
Try getting the value for your attribute, like so:
$('#domToChange').attr('someattribute');
//or
$('#domToChange').attr('someAttribute'); // i know you've tried this, but pls check demo
Demo here. On my machine, browser Chrome Version 28.0.1500.95 m, it just works fine.
OK, this is a hit and miss kind of thing (but I believe it be an accurate explanation), but the real explanation for why it is happening lies here.
You need to understand that jQuery is an object that is initialized. So the jQuery object takes time to initiatize. As it says,
is very important to make the distinction between jQuery object and native DOM elements. Native DOM methods and properties are not present on the jQuery object, and vice versa.
So it is not necessary that the jQuery object gets initialized at the same time the DOM gets initialized.
Also, all scripts that are passed have a defer attribute. This is mostly browser dependent.
As it says,
When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering.
And it can sometimes delay the execution of the script. Hence the different result according to different people.
You have to enclose the code like this:
$(function(){
$('#domToChange').attr('someAttribute');
});
So that the code is executed when the DOM is ready.

How to find the snippet of JavaScript that modifies an element?

The page I'm trying inspect has a hidden <input type="hidden" name="Foo" value="123 /> element on a page, where Javascript/AJAX modifies the value. I'm trying to find where on earth in Javascript is the code that modifies this value from time to time.
Is there a tool that could help me find the places in javascript that use/modify that element? Does Firebug provide this, if so, how?
Note: If tried looking for "Foo" in the code, but I haven't found any matching titles. There's JSON and Mootools loaded, +application specific code, which results several thousands lines of code. The element is probably accessed indirectly.
Firebug 1.5 will have "Break-on-Modify" on the HTML panel. See http://getfirebug.com/doc/breakpoints/demo.html#html - Break on DOM (HTML) Mutation Events.
How do you know that the javascript is modifying this value? Since it looks you already know when it's called (since you know it changes), I would suggest a breakpoint in Firebug in the first event that initiates the changing (probably an onclick attribute in other element).
It's kind of hard telling you a "generic" way of knowing where in javascript it's changing Foo's value since there are a lot of different approachs, different libraries, each one with it's syntax.
For example, if you tried searching "Foo" and didn't find it, the script may be traversing the DOM and changing the input's value as a "first child of something". I would try to search for names or ids of input's parent elements and understand the code from there.
I usually just try to understand the javascript logic from every script I use with Firebug's debugging techniques - but just on the script that uses the libraries.
If Firebug doesn't let you define breakpoints on setting some value, you could insert something like this in the page (Firefox-only):
$("textarea")[0].__defineSetter__("value", function(val) {
alert("called");
})
And either breakpoint on the function in Firebug or use console.log or whatever to dump the stack to the firebug console.
I remember seeing somewhere a presentation on Firebug plans, which included a section on various kinds of breakpoints to be supported, but I can't find a link to it right now.
[edit] The above is for the case the value is set by assigning to the value property: .value = .... If you need to catch the moment an attribute is changed (.setAttribute("value", ...)), you can use DOM mutation listeners.

Categories

Resources