Coding tips
From GreaseSpot
This page is for general coding tips, as opposed to site-specific tips or staple functions.
Contents |
[edit] location.replace() vs. location.href
Though code like
location.href = newURL;
sees much use, sometimes
location.replace(newURL);
is what you want. The first line navigates to newURL, with the browser "Back" button ending up pointing to the current page; the second line replaces the current page in the browser history, as though you never were there at all.
location.replace() is appropriate when your script is meant to replace a page (e.g. skip an advertisement splash screen), since the user typically does not want to see that when hitting the "Back" button. location.href = is appropriate when you just want to redirect somewhere.
If your intention is to refresh the current page, then this is what you want:
location.reload();
[edit] array.forEach
Though not very well-known, Firefox supports a forEach method on arrays. Rather than
for (var i = 0; i < array.length; i++) {
do_something(array[i]);
}
, you can simply do
array.forEach(function(element) {
do_something(element);
});
or more concisely:
array.forEach(do_something);
The callback function actually receives three arguments, though you will often ignore the last two. This example uses all of them:
array.forEach(function(element, index, array) {
GM_log("Element " + element + " in array " + array.join(", ") + " with index " + index);
});
Within a forEach loop (being a function call), return can be used for the same effect as continue (in a for loop) and throw/catch can be used instead of break.
A similar construct can be used to iterate over array-like objects such as the HTMLCollections returned by DOM functions and properties. For example:
Array.forEach(document.links, function(link) {
do_something(link);
});
[edit] Read HTML within an iFrame
I wanted to find a way to be able to read the HTML source within an iFrame. Here's how I did it:
var html = window.frames['iframe_name'].document.documentElement.innerHTML;
The html variable now contains the entire source code of the website within the iFrame. It does have some limitations, however. You can only read source from the same server. For example:
<html> <body> <iframe name="iframe_name" src="http://www.awesomedomain.com/some_folder/some_page.html"></iframe> </body> </html>
You could only get the code from iframe_name if your page was hosted in http://www.awesomedomain.com. This is a security feature within Firefox. If you try it, the JavaScript console will respond by saying "Permission Denied."

