Grab content from another page by javascript or jquery

Asked

Viewed 20,983 times

9

I need to get content from another page inside the site using Javascript, I tried using ajax, but gives this error "Blocked cross-origin request: The same origin policy (Same Origin Policy) prevents reading the remote resource on https://www.google.com/. (Reason: CORS header 'Access-Control-Allow-Origin' is not present)."

I need to take the value of some Divs and put in variables, I need to do this using Javascript.

How to do this?

Code used:

function showUser(str) {
if (str == "") {
    document.getElementById("cabecalho").innerHTML = "";
    return;
} else {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("cabecalho").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","https://www.google.com");
    xmlhttp.send();
    }
}

showUser("str");
  • I’m guessing you don’t control the server that hosts that content, right? You control a server where you can install e.g. a PHP script, which can request the server with the contents?

  • No, I can only include HTML, Javascript and CSS code.

  • You mentioned in another comment that this is for an online store. The store already has HTTPS on?

  • I found that I can only import pages from the site itself if I try to import google for example does not work. (Not even any other site)

  • Still need to import file from another page, help me. Nothing works...

  • from my point of view the only way to make this request is by consuming a Webservice/API of the site in question, if there is no such feature on the site it is not possible to obtain the data with language limitations

  • There is no way to get information from another page just with Javascript?

  • @Felipejorge I left an example there in my reply, it runs until here in the OS, type any address in the demonstration there that already comes out the result right there

Show 3 more comments

5 answers

5

You can use the function load(). Example of use:

$( "#resultado" ).load( "ajax/teste.html #container" );

That is, the ID element resultado will receive the content that is in the ID element container page teste.html.

  • 1

    If I understand, @Felipe is having CORS problems - the other server is not under his control and has not explicitly authorized access via Javascript.

  • 1

    Hmm, it might be. If that’s the problem I delete my answer, ;)

  • I am making an API for integrated store, but I do not have access to PHP and have to use only Javascript, this Javascript it is inserted into the code by a form. It’s not up my control the code.

  • @Felipejorge So my answer has no relation to your problem?

  • 1

    This is the solution I tried, but it does not solve my problem. However it is useful as it can inform other users.

  • "Integrated store"... by chance you have already called HTTPS on your website?

Show 1 more comment

5

To make a request between domains, as you are doing in the example, you need to set the header Access-Control-Allow-Origin on the requested page.

Since you are using the Google site as an example, it will not be possible, but if the page is yours, you can set this header yourself.

A way to use the page would also be using a iframe, but I believe that’s not what you want.

UPDATE

Example to set the header in PHP

// permite que qualquer site acesse (destinada a apis públicas)
header("Access-Control-Allow-Origin: *");

// permite que um site específico acesse (destinada a apis privadas)
header("Access-Control-Allow-Origin: https://seu.site.com.br");

5


Ajax for security does not cross Omain, but there is a Brazilian way to do this I will leave the example running here in the OS to fail :

$(document).ready(function(){
	$("button").click(function(){
		site = $("#site").val();
		$.ajax({
			url: site,
			type: 'GET',
			success: function(res) {
				var headline = $(res.responseText).text();
				$("#conteudo").html(headline);
			}
		});
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<head>
<!-- Scripts Javascript -->
<script type="text/javascript" src="http://projetos.lucaspeperaio.com.br/ajax-cross-domain/jquery.xdomainajax.js"></script>
<title>jQuery e Ajax Cross Domain</title>
</head>

<body>
<input type="text" id="site" value="http://" />
<button id="acessar">Clique para obter o conteúdo deste site</button>
<div id="conteudo" style="background:#EEF0A6"></div>
</body>
</html>

Edit - Note of clarification:

  • James Padolsey’s . js file (http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/) who had the idea of joining the YQL service( yahoo web service ) to work with jQuery. But the question most people are asking me is whether using this web-service is safe. Then taking a closer look at whether it is feasible to use a third party service or whether it is safe or not. then...

It is possible to download the project and build your own web service, or make a Fork of the original project and make its customizations if you do not want to take this risk ;)

github https://github.com/yql/yql-tables

  • 1

    -1. Explanation: The answer introduces three undesirable factors - 1) a Middle man that captures all content requested by the browser, exposing information and adding complexity to the solution: 2) does not work for requests internal network: 3) The answer does not show how the proxy was implemented, and is therefore incomplete. I suggest to post the code of the proxy.

  • 3

    The code is making a call to the yahoo api that then accesses the landing page, i.e., you become dependent on the yahoo service being available, in addition to having one more site involved in the request.

  • Supplement the answer with more details on how to yahoo query language was used to perform the request between domains.

  • How would I use this code without having to click the buttons (run when loading the page)? Despite being a criticized response, it works with different protocols correct? Depending on the Yahoo server would be a problem, but it is a valid answer since it works.

  • 1

    I passed the fiddle because I already posted the practical example here, but briefly just remove the embellishments, remove the input button and pass the url directly in the ajax url parameter follow link http://fiddle.jshell.net/9ee2c1fa/

  • The amendment leaves the most complete answer, -1 reversed.

  • Well this solution solves the problem, but I will assess if there are other ways to do before marking as solved.

  • @Sneeps Ninja. With different protocol is not working anymore. Could you help me?

  • @Felipejorge gives a revised in their codes, maybe if the case opens a question by posting the source code, at first I tested again the continues working

  • @Sneepsninja can you help me with my question, please? I could not execute this example of this question: http://answall.com/questions/75104/pega-conte%C3%Bado-de-outra-p%C3%A1gina-com-jquery

  • I think this script only works cross if the site protocol is http. Because I try my https protocol and the problem. If I try to localhost it works. Something is blocking it.

  • @Sneepsninja , I discovered the problem, went to the console and found that the algorithm only works cross Domain if it is http protocol. That is if the site has http protocol then it works by importing the http and http protocols, but I need something that works for both http and https. ( Because I’m making an API for a website and it can happen that the person has both http and https protocol)

Show 7 more comments

2

Or Apache httpd.conf // allows any site to access (intended for public schools) Header set Access-Control-Allow-Origin "*"

// allows a specific website to access (intended for private websites) Header set Access-Control-Allow-Origin "https://seu.site.com.br"

0

I solved this problem using an iframe to access the external url, so there is no need to make any changes to the target application.

<iframe src="http://seuServico.do"></iframe>
  • This is WELL depreciated, and evades the purpose of the question.

  • Good alternative when you cannot follow the previous suggestions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.