Search code examples
javascriptxmlhttprequestxmlhttprequest-states

Getting HTML Source Code via XMLHttpRequest [JavaScript]


XMLHttpRequest works for first url but it doesn't work for second url.I think this function doesn't work for dynamic web pages.I also tried ajax to get html source but it didn't work too.What can I do?How can I change this code to work for second url?

<script language="Javascript" type="text/javascript">

function getSource(url)
{
    var req = new XMLHttpRequest();
    req.open(
        "GET",
        url,
        true);
    req.onreadystatechange = statusListener;
    req.send(null);
    function statusListener()
    {
    if (req.readyState == 4) 
        {
            if (req.status == 200)
            {
                var doc=req.responseText;
                alert(doc);
            }
        }
    }
}

url1 = "https://pages.github.com/";
url2 = "https://stackoverflow.com/";

// This code WORKS
getSource(url1);

// This code DON'T WORK
getSource(url2);
</script>

Solution

  • I ran your code in a JSFiddle, and I got an error message saying it is a CORS issue. You can view these error messages by opening the Javascript console in your browser of choice.

    Error message as seen in the Javascript console

    CORS (Cross-Origin Resources Sharing) issues arise when you don't have the sufficient permission to access resources between different domains. Each web server has policies set up that determine the rules for accessing these files, and Stack Overflow's security settings are set up to disallow that kind of access to their site. You can read more about CORS here.