Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a page's complete source using Javascript

I'm trying to capture and post all JS errors in a page to a Django view. I'm doing something like this.

<script>
    window.onerror = function(errorMsg, file, lineNumber) {
        post_data = {error: errorMsg, file: file, 
        location: window.location.href, lineNumber: lineNumber,
        ua: navigator.userAgent};
        jQuery.post('/js_errors/', post_data);
    }
</script>

The Question: I'd like to add the actual line as well. How do I get the line from the page source, given the line number?

So far, I've tried this (accounting for all kinds of newline characters):

document.getElementsByTagName('html')[0].outerHTML.split(/\r?\n/)[lineNumber];

However, this doesn't give me the correct line number. What am I missing here?

like image 855
GPX Avatar asked Aug 01 '13 11:08

GPX


People also ask

How do I collect page source?

To view only the source code, press Ctrl + U on your computer's keyboard. Right-click a blank part of the web page and select View source from the pop-up menu that appears.

Can JavaScript read the source of any Web page?

If for some odd reason, you wanted to view the source code of another page without having to actually browse to that page and click “page view source,” you can use JavaScript to do so. In the example below, I use the “window.

What is the source code of a page?

The HTML code of a website is also called source code. Source code is an important part of SEO because it determines the correct execution of a webpage and gives information about possible optimization potential. Source code optimization is therefore part of technical SEO.

How can I see the JavaScript code of a website?

For most browsers, to view inline JavaScript in the HTML source code, do one of the following. Press the Ctrl + U keyboard shortcut. Right-click an empty area on the web page and select the View page source or similar option in the pop-up menu.


1 Answers

Not particularly efficient, but should get what you're after (i.e. doctype and all):

lineNumber = 23;
errorLine = null;
$.post("",function(source) {
    errorLine = source.split(/\r?\n/)[lineNumber];
});
like image 169
MDEV Avatar answered Sep 22 '22 21:09

MDEV