0

I'm able to use document.getElementById() fine when working with the same page, but I haven't been able to figure out how to get the element by it's ID from a different page. So far, my guess has been to use jQuery's $.get function, which I haven't gotten to work either.

$(function() {
    $('#inputform').submit(function(e) {
        e.preventDefault();
        var rawnum = $('#inputform').serialize();
        var num = rawnum.split("=")[1];
        var url = "http://google.com/"; //this url is an example
        $.get(url, function(data, status) {
            $("html").html(data);
        });
    });
});
  • 1
    [SAME ORIGIN POLICY](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript) Learn about it. – epascarello Jul 01 '13 at 12:53
  • If you've set up CORS so you can access the page, you'd then use `otherPageWindowRef.document.getElementById` to get it, and you may have to use `document.importNode` to have access to more than just the reference once you have found it. – Paul S. Jul 01 '13 at 12:56

1 Answers1

4

Your page would need to be the opener and the other page and, more importantly, the two pages would have to be served by the same origin (see same origin policy) or that other page would have to be served with CORS headers precising this access is authorized.

As your example shows, this is obviously not the case so you simply can't access the element.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I'm not sure I understand same origin policy, I've been able to retrieve data from other pages in the past, using Java and PHP, but I haven't been able to figure out how to do this using jQuery and Javascript, which is what I need at the moment. –  Jul 01 '13 at 12:55
  • 2
    @KeybordPiano459 The same origin policy is a security feature in _JavaScript_ which prevents you from retrieving data from different origins (read domains, protocols, etc) unless the other origin expressly gives permission for such retrieval. – Paul S. Jul 01 '13 at 12:59
  • @PaulS. Ah okay, I didn't understand that this specifically applied to Javascript. –  Jul 01 '13 at 12:59
  • @KeybordPiano459 it's to stop malicious websites being able to access all your bank details, webmail, private information, etc. through your browser just because you hit their page, because remember, unlike other platforms, you use your browser to access these things. – Paul S. Jul 01 '13 at 13:02
  • @PaulS. Would this even prevent me from doing actions such as reading an RSS feed in Javascript? –  Jul 01 '13 at 13:03
  • @KeybordPiano459 No : the RSS server just has to set the appropriate CORS header. See http://enable-cors.org/ – Denys Séguret Jul 01 '13 at 13:06
  • This other question is relevant [**Same Origin Policy, Javascript/jQuery AJAX and retrieving an RSS XML feed**](http://stackoverflow.com/q/4686497/1615483) – Paul S. Jul 01 '13 at 13:08