简体   繁体   中英

Find element attributes on different domain using Javascript

Is it possible to find the attributes of certain elements on one website and display them on another website? For example, if I have website 1, can I use Javascript/jQuery to find out the size of a specific image or div on website 2 and display those attributes on website 1?

If I can't do something like that with Javascript, is there an alternative way of going about accomplishing that specific example?

1 . What you are trying to do can't be done using any AJAX library. Browsers' cross-domain policy won't allow you to do this.

But you can do this with a combination of php (or any other server-side language) and AJAX. Create a php script like this:

<?php
    $url=$_POST['url'];
    if($url!="")
        echo file_get_contents($url);
?>

Let us say the script's name is fetch.php . Now you can throw an AJAX call from your jQuery code to this fetch.php and it will fetch the HTML code for you.

2 . The same origin applies. try this code and you'll face security error,

$.get("other web page site", {}, function(content){
   $("#receipe").html(content)
}, "html")

3 . Using Greasemonkey, it is possible to make third-party requests. A jQuery-oriented tutorial is offered on this page . The short answer it to have Greasemonkey make the request on your behalf. Replace all your XMLHttpRequest objects with GM_xmlhttpRequest objects.

Useful links,

Can Javascript read the source of any web page?

http://www.sitepoint.com/forums/showthread.php?836704-How-to-get-contents-of-3rd-party-website-into-javascript-variable

Sadly because of same origin policy you can't access the DOM on a different domain. If you control both domains you maybe able to use CORS and modify the server HTTP headers to allow Javascript access.

The workaround to this is to use a server to act as a proxy between the two websites. So you would have a server side script on website 1 that would send a request to website 2 and return the content from website 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM