-1

I'm trying to get the source code of a specific webpage, then find a special <div> in it.

I don't want to open the webpage in a browser, because what I'm doing is supposed to run on a mobile platform using React Native (which is not our concern here).

How can I get the page source without opening the webpage using vanilla JavaScript (no jQuery)?

Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
Mohammad Siavashi
  • 1,192
  • 2
  • 17
  • 48
  • Possible duplicate of [Can Javascript read the source of any web page?](http://stackoverflow.com/questions/680562/can-javascript-read-the-source-of-any-web-page) – Mike Cluck Jan 26 '16 at 18:18
  • I'm not sure of the purpose of this. Maybe use a headless browser of some kind, like Phantom or Zombie? – sg.cc Jan 26 '16 at 18:20
  • 1
    Any code which can create an HTTP request and read the response can view the original source of a page... – David Jan 26 '16 at 18:21
  • You can use jquery like `$.get()` to do this, I guess. – dvenkatsagar Jan 26 '16 at 18:22
  • What do you mean by "read the source code"? Do you mean read the JSP, ASPX, PHP code that generates the HTML sent to the browser? It's possible to do that using Javascript, but only if the server supports the WebDAV translate request header. ALSO - Are you accessing the a page across domains? – Yogi Jan 26 '16 at 18:26

3 Answers3

2

With vanilla JS:

  var x = new XMLHttpRequest();

  x.onreadystatechange = function(){
    if( x.status === 200 && x.readyState === 4) {
      console.log(x.responseText);
    }
  }

  x.open('GET', '/my/file/at/address.html', true);
  x.send();

That will give you the raw text contents of address.html. However, due to its being just text, you won't be able to do things like document.querySelector('#mydiv'). I would once again recommend a headless browser, depending on what exactly you want to do.

sg.cc
  • 1,726
  • 19
  • 41
  • is there any headless browser i can use on mobile devices ? zombie is using node.js then its not able to run on android devices . – Mohammad Siavashi Jan 27 '16 at 00:27
  • 1
    Why not spoof Zombie as if it's coming from a mobile device? Depending on how your target site determines the user agent (which is almost always going to be from the `useragent` string), just have Zombie present itself as a mobile browser. – sg.cc Jan 27 '16 at 17:29
1

Using jquery, you can get the data like this:

$.get("test.html",function(data){
  console.log(data);
});
dvenkatsagar
  • 936
  • 7
  • 22
0

I think you can use .load():

$("#dummy").load("link");

And make #dummy div hidden:

<div style="display:none" id="dummy"></div>

In this way you will have loaded HTML in div dummy and then you can directly work with it without parsing the result.

MrOnlineCoder
  • 333
  • 3
  • 15