To get text present in a browser window - javascript

I want to get text present in a window that I opened using following code
var yy = window.open("http://www.vignanuniversity.org/");
Now I want to get text present in that window for that I used
var responseText = yy.html();
I' getting the error in chrome console as
Protocols, domains, and ports must match.
So I'm using cross domains, then how to get solution to my problem.

There is no way to access another webpage's window contents. However, you could have the javascript make a request to your server on the backend to make the request for you.
Javascript
//Gets the contents of the web page using the backend server
getContents("http://www.vignanuniversity.org/", function(contents, responseCode){
alert("Page received with status: " responseCode);
alert(contents);
});
//Takes the URL as page and a function to handle the result.
//retFunc has one parameter, which is the response
function getContents(page, retFunc){
var myServer = "/php/getRemote.php";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
retFunc(xmlhttp.responseText, xmlhttp.status);
}
}
xmlhttp.open("GET", myServer + "?url=" + page);
xmlhttp.send();
}
PHP
//Location: /php/getRemote.php
$url = $_GET["url"];
echo file_get_contents($url);
This will allow you to effectively grab get the contents of a website. You just won't be able to access modified content

Related

Trying to build query string and scrape Google results

I'm trying to build a Google query string, make a request to that page, scrape the HTML, and parse it in a Chrome extension, which is JavaScript. So I have the following code:
var url = "https://www.google.com/search?#q=" + artist + "+" + title;
searchGoogleSampleInformation(url);
function searchGoogleSampleInformation(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
return parseGoogleInformation(xhr.responseText, url);
}
}
xhr.send();
}
function parseGoogleInformation(search_results, url)
{
var link = $(".srg li.g:eq(0) .r a", search_results).attr('href');
}
The parse method just grabs the url of the first search result (which is not want I'll end up doing, but just to test that the HTTP Request was working). But link is undefined after that line. Then I used alert(url) and verified that my query string was being built correctly; I copied it from the alert window and pasted into another tab, and it pulled up the results as expected. Then I opened a new window with search_results, and it appeared to be Google's regular homepage with no search at all. I thought that problem might be occurring because of the asynchrony of the xhr.open call, but flipping that didn't help either. Am I missing something obvious?
It's because "https://www.google.com/search?#q=" + artist + "+" + title initially has no search results in the content. Google renders the page initially with no results and then dynamically loads the results via JavaScript. Since you are just fetching the HTML of the page and processing it the JavaScript in the HTML never gets executed.
You are making a cross domain Ajax call, which is not allowed by default. You cannot make a cross domain call unless the server supports it and you pass the appropriate headers.
However, as you mentioned you are building a Chrome extension, it is possible by adding a few fields in the manifest file: https://developer.chrome.com/extensions/xhr#requesting-permission

Get text from a link in javascript

I am trying to get text from a service on the same server as my webserver. The link is something like this:
http://<OwnIPadres>:8080/calc/something?var=that
This is my code:
function httpGet(theUrl)
{
alert(theUrl);
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
alert("text: " + doc.responseText );
document.getElementById('ctm').text = doc.responseText;
}
}
doc.open("get", theUrl);
doc.setRequestHeader("Content-Encoding", "UTF-8");
doc.send();
}
The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?
Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.
I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an
Access-Control-Allow-Origin: http://:8080/
in your header (however that will only get you the most modern browsers).
Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.

Javascript: Find browser windows open with the same domain

Is there a way to get a list of all the open browser windows if they are from the same domain as the window that is trying to get the list?
In general, no.
Unless there is a "connection" between the windows (e.g., one window opened all the other using window.open), browser windows can't interact because of security reasons.
Edit:
If you assign a name to your window, you can regain control over it after refreshing the parent page.
windowVar = window.open('somePage.html', 'windowName'); opens a child window with name windowName.
After refreshing the parent page, windowVar = window.open('', 'windowName'); re-associates the variable windowVar with the window of name windowName.
Now, windowVar.location.href= 'logout.html'; lets you log out your user.
Edit:
Assuming you use PHP, you could do something like this:
Create logged.php with a function logged_in that verifies if the session ID is still valid.
<?php
if (isset($_GET['sid']))
if (logged_in($_GET['sid']))
echo "in";
else
echo "out";
?>
Include check() function in your pages.
function check()
{
var url = "http://redtwitz.com/test/logged.php?sid=" + sessionId;
var request;
try
{
request = new XMLHttpRequest();
}
catch(error1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(error2)
{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
}
request.open("GET", url, false);
request.setRequestHeader("User-Agent",navigator.userAgent);
request.send(null);
if(request.status==200)
if(request.responseText == "out")
window.location.href = "logout.html";
}
Call check function every 5 seconds.
<body onload="setInterval(check, 5000);">
Alternatively, you can implement Chrome extension and do your task by using extension api: http://code.google.com/chrome/extensions/tabs.html
But it will work in Chrome browser only.

Access-Control-Allow-Origin error when trying to get resources from site in same domain?

I'm merely trying to grab the html from one of my other sites on the server and print it on the current site. Here's basically what I'm doing:
// The object
var xmlhttp = new XMLHttpRequest();
// When a button is pressed, we get the html
function printJSON(action)
{
otherURL = "http://www.my.domain.com/other.php?action=" +action;
xmlhttp.open('GET',otherURL,true);
xmlhttp.send();
}
// and then print it in this div
xmlhttp.onreadystatechange = function
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
$('JSON_output').innerHTML = xmlhttp.responseText;
}
}
and the error I'm receiving is:
XMLHttpRequest cannot load http://www.my.domain.com/other.php?action=SEARCH. Origin http://my.domain.com is not allowed by Access-Control-Allow-Origin.
Which seems strange, because this is one site on the server trying to access another site right within the same folder. Is there something I need to adjust on my server? An attribute in xmlhttp I need to set?
Cheers!
http://www.my.domain.com and http://my.domain.com are two different domains (note the www) according to the JavaScript same-origin policy.
If www.my.domain.com and my.domain.com point to the same place, the simplest solution would be to make otherURL relative; start it with "/other.php?action="; that way, it will always be on the same domain as your page.
If they do not, point to the same place, there is a much more complicated solution involving your server outputting additional headers called Cross Origin Resource Sharing; here's an overview.

problem in refreshing the page after making two ajax calls

Problem I am making ajax call to server1 i.e. csce and once I got the response I am sending the response as contents to server2 i.e.yahoo server after getting response from there I want to refresh the page or atleast redirect it to the same page. Both ajax calls are working fine. The contents I am sending are also saved the only problem is that I have to manually refresh the page to see the changes. I want to refresh the page once the contents are saved on yahoo. I tried reload and redirect commands in success function of yahoo. But nothing works. I can see the both ajax calls in the HTTPfox but not the redirect.
The url from which i am making calls is different from the url where contents are saved thats why I need to refresh the page to see the changes. i.e. I am saving in yahoo/save while sending contents and seeing changes at yahoo/edit.
I am not sure where I am going wrong. Here is my code I am using. Can anyone suggest where I am going wrong. If my problem is not clear kindly do ask me to clarify more. Thanks.
This code is the code:
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
var substring=xmlHttp.responseText;
alert(substring);// I am able to see the text which is returned by the server1 i.e csce
var handleSuccess = function(o)
{
if(o.responseText !== undefined)
{
console.log(o.responseText);
**window.location.reload()** // also I tried to redirect it to the same site but that also not works
}
};
var callback ={ success:handleSuccess, failure: function(x) {
console.error(x) }, argument: ['foo','bar']};
var request = YAHOO.util.Connect.asyncRequest('POST','http://yahoo.com******', callback, substring);
}
}
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://cse*****id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
Do you just want to display the content in your page? Why don't you try something along the lines of document.getElementById('divID').innerHTML = xmlHttp.responseText;?
With divID being the id of a div that you want to fill the content with.
try following in the handleRequestStateChange function
window.location.href = window.location.href;

Categories