Sunday, December 30, 2012

Retrieving a partial content


You can send a Range header:
request.setRequestHeader("Range", "bytes=0-9999");
request.send(null);
Note that the server might ignore this header and you will get the usual response back. In most cases the response will be "206 Partial Content" however with exactly 10000 bytes of data. Content-Rangeresponse header indicates which part of the file you've got, e.g.request.getResponseHeader("Content-Range") might give you bytes 0-9999/1234567 (here 1234567 is the total size of the file).
Obviously, you can also do request.setRequestHeader("Range", "bytes=100000-119999"); to get data from the middle of the file.

The following code can be used to download the first 10k of a sites html as per the first part of the question...
Lets say I only need first 10kb of the page
function getURL(url, limit, callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if ( request.readyState == 4 ) {
            if (request.responseText!=0) callback( request.responseText, request.status );
        } else if (request.responseText.length >= limit) {
            // If limit is exceeded
            var result = request.responseText;
            request.abort(); // Cancel request
            callback( result, request.status );
        }
    };
    request.overrideMimeType("text/html");
    request.open( "GET", url, true );
    request.send();
}

getURL('http://www.google.com.au', 100000, debug);
//getURL('http://paez.kodingen.com/testy.png', 100000, debug);

function debug(responseText, status) {
    console.debug('length of responseText '+responseText.length);
    console.debug('responseStatus : '+status);
    console.debug('responseText :\n'+responseText);
}
Note
It should be noted that this wont get exactly the size you specify as their is no way to say how often the readystate will be called. Also, I force it to be text otherwise their may not be a responseText.

Here when readyState is not 4, which mean loading state; So here we can abort request when size is exceeded.

jQuery data() method


$('<some selector>').data()
will return you all the data section attached to element.

Friday, December 28, 2012

Modifying Console.log


Go in console mode ( Control Shift J on Windows ) , enter this :
console.nativeLog = console.log;
Then enter this
console.log = function( a, b ){ if(a=="extension") console.nativeLog( b ) }
The first line keeps the native implementation in a safe spot. The second line does pretty much what you request.

Awesome way to use this :)

jquery === $

the jquery === $ is used to check whether jquery uses $ as its replica

How to detect whether console is open


window.onresize = function(){
 if((window.outerHeight-window.innerHeight)>100)
   alert('hello');
}
Above code will fail when console is undocked and when the window sizes are manipulated and when page is loading.
You may also get false positives when working with certain frame setups.
The bottom line is that there is no documented way to reliably detect the inspector, and no way at all to detect it when undocked. This is most likely due to security concerns. A malicious webpage could conceal its payload when the inspector was open, making it more difficult to debug.

debugger;

debugger; is an amazing keyword for debugging

CSS Diff


As a proof of concept, we can do a small trick here and avoid creating extension. Chrome keeps elements you select via 'inspect element' button in variables. Last selected element in $0, one before that in $1 etc. Basing on this, I've created a small snippet that compares last two inspected elements:
(function(a,b){    
    var aComputed = getComputedStyle(a);
    var bComputed = getComputedStyle(b);

    console.log('------------------------------------------');
    console.log('You are comparing: ');
    console.log('A:', a);
    console.log('B:', b);
    console.log('------------------------------------------');

    for(var aname in aComputed) {
        var avalue = aComputed[aname];
        var bvalue = bComputed[aname];

        if( aname === 'length' || aname === 'cssText' || typeof avalue === "function" ) {
            continue;
        }

        if( avalue !== bvalue ) {
            console.warn('Attribute ' + aname + ' differs: ');
            console.log('A:', avalue);
            console.log('B:', bvalue);
        }
    }

    console.log('------------------------------------------');
})($0,$1);
How to use it?
Inspect two elements you want to compare, one after another, and paste the code above to console.
Result
sample output from provided snippet

Wednesday, December 26, 2012

monitorEvents()

monitorEvents() is an excellent tool of console which will monitor all events happening in an element passed!

monitorEvents($$("div"))

more information http://www.youtube.com/watch?v=4mf_yNLlgic

console.dir()

console.dir() gives a dom Level write to console rather text bases opposed to console.log()

Console.time

console.time("Some Name");

console.timeEnd("Some Name"); using these amazing features you can figure out time taken by this function execution.

the names has to match

Code to set focus for newly created stuff

chrome.tabs.update(tab.id, {url: url, selected: true}); will set focus to new tab created.

Download CRX Code


For one of my extensions I had to download other CRXs automatically knowing only extension ID. I solved this by opening the following URL:
http://clients2.google.com/service/update2/crx?response=redirect&x=id%3D<EXTENSION_ID_HERE>%26uc%26lang%3Den-US&prod=chrome
this page will forward you to that https://clients2.googleusercontent.com/crx/download/address.
I don't remember already how I came up with that URL (it was either in page source somewhere or I used network sniffer), but it has been working great for me since last December, so it looks reliable.

Tuesday, December 25, 2012

base tag in HTML

<base> tag in HTML will serve base path(when set through href attribute <base href="http://www.w3schools.com/images/">  ) for all relative URL's in the page( and this can be overwritten through http:) , and also defines global target property(when set through <head>
    <base target="_blank">
</head>
target property and anyways this property can be over ridden through inline settings of attributes.

Make sure to specify http:// (not just www.) in the links or they will open relative to the extension

Programatically open options

chrome.tabs.create({url:"options.html"});

getcurrent()

getCurrent() should not be used at all from non tab context, ex: popup or background page, it should be used only when the current call is made from a tab context.

getCurrent should be used only inside extension's own pages that have a tab associated with them (options.html for example), you can't use it from a background or popup page

Reload Chrome Extensions

Use chrome.extension.getViews() and call window.reload() function on it to reload it.

Monday, December 24, 2012

document.defaultview

document.defaultview property returns window object of current page

TODO

differences between window object of page and window object of content script

Saturday, December 22, 2012

Debug Log of Chrome


%USERPROFILE%\Local Settings\Application Data\Google\Chrome\Application\debug.log

CSS Specificity

Focus in chrome


 // In Chrome, caller is null if the user initiated the focus,
  // and non-null if the focus was caused by a call to element.focus().
var causedByUser = (onfocus.caller == null);
node Types
https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType




Chrome history location

http://computer-forensics.sans.org/blog/2010/01/21/google-chrome-forensics/


Here’s a tutorial: Google Chrome Forensics. Some notes:
  • The sqlite3 databases are “locked” when Chrome is running, so you might have to either close Chrome or copy the databases to a separate file before reading them.
  • In the History database, the visit_time is μs since 1601-01-01 (1/10th the Windows filetime) even if you’re on Mac or Linux, so to convert it to Unix time (s since 1970-01-01) you have to scale and subtract 11644473600 = new Date(1970, 0, 1)/1000 - new Date(1601, 0, 1)/1000.
  • E.g., Find the last 10 URLs I visited: select urls.url, datetime(visit_time/1000000 - 11644473600, 'unixepoch', 'localtime') from visits left join urls on visits.url = urls.id order by visit_time desc limit 10;
  • The visits.transition&255 is an enum found in page_transition_types.h. See the descriptions within the extension documentation on history.

Detecting copy events in a Page


//register event listener for copy events on document
document.addEventListener('copy',onCopy,true); 
will let you trace all copy events

chrome://version

Profile PathC:\Users\sudharshan\AppData\Local\Google\Chrome\User Data\Default

chrome version page gives you profile path where extensions are saved.


  1. Visit chrome://version.
  2. Look at Profile Path.
  3. Extensions can be found in the Extensions subdirectory of the path you found at the previous step.

tab Id in chrome

Tab Id in chrome can never be zero but it can be -1 also

chrome://crashes

You can get your crash id from here.

window.open()


// The maximum number of popups that can be spawned from one page.
static const int kMaximumNumberOfUnacknowledgedPopups = 25;
The above is an extract from chrome source code, which says and intentional upper bound of 25 on window.open calls. See Chromium bugs 2632 and 3382for background, but in brief, the idea is to prevent denial-of-service (both UI-wise and memory-wise) attacks from pages that open popups indefinitely.
Extension APIs like chrome.tabs.create are not subject to these APIs, since extensions are privileged access already.
Window.open("\n"); opens a duplicate popup window.
window.open("\r"); opens a duplicate popup window.