Javascript: Find browser windows open with the same domain - javascript

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.

Related

Detect When Specific Tab Closes

I have a .php file running that is generating a downloadable file; when the .php file runs it opens a tab in the browser. Occasionally the .php file takes up to 15 seconds depending on the conditions to create the file.
I would like to know when this tab is open generating the downloadable file and when it closes. This way I can have some sort of loading message displayed while the file is being generated. When the .php file is done creating the file it automatically closes the tab.
Code:
var win = window.open(download, '_blank'); //opens the php file which generates the file.
if (win)
{
win.focus();
//have some sort of message stating to wait for the file to download here and then close it when the php file finishes running.
}
else
{
alert("Please allow popups.");
}
closePopup2();
I would suggest not opening a PHP file in a new tab, but using XMLHttpRequest(), you can find a guide on how to use it on MDN
You can use it like this:
function reqListener () {
console.log(this.responseText); // Will log full output of page
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", download);
oReq.send();
Give your window a unique id so the script will know which one to check (maybe needs to be random if opened/closed multiple times). I don't know if you need to focus, and popup permission is for you to figure out, but I think following should work:
var win = window.open(download, 'windowID', 'width:300px;height:300px');
win.document.write("<p>One moment please!</p>");
win.focus();
var test = setInterval(function() {
if(win.closed) {
clearInterval(test);
// do you stuff here after window closed
}
}, 500);

To get text present in a browser window

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

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.

Why does my AJAX loading fail the first time through when hosting my MVC3 project in IIS7?

I was writing an mvc application with a few tabs. I noted that when hosted on IIS 7, the home page has a link triggering a JavaScript function to load content via AJAX.
It doesn't work on the first page load, however when I visit some other tab and come back to the home page and click on the link it works perfectly. Can someone tell me the reason for this or how to avoid it?
The Loading Code
function GetLabels(project) {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("light").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", "/Home/GetLabels?project="+project, true);
xmlHttp.send();
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
document.getElementById("light").innerHTML =
"<img src='Content/load.gif' alt='Please wait' />";
}
The Link that Triggers it
Click here
You should not hardcode urls like this:
xmlHttp.open("GET", "/Home/GetLabels?project="+project, true);
You should always use url helpers to generate them:
xmlHttp.open("GET", "#Url.Action("GetLabels", "Home")?project=" + encodeURIComponent(project), true);
Now your AJAX request will work no matter whether you are hosting in Visual Studio's built-in server or IIS. The reason why your code doesn't work in IIS is because in IIS your application is hosted ni a virtual directory that you must include in your url. So the correct url is not /home/getlabels but /appname/home/getlabels which is something that the url helper takes into account.
Also since you are using a GET request the web browser might cache the result and never send a request again to the server. To avoid this you should append a random query string parameter to the url or use the POST verb.

How to send a variable from ajax success to a template?

Is it possible reload a page without refresh (silently) ?
Here is an example where page reload automatically. But you can easily see that the page is refreshing after certain time interval. I don't like this where end user is getting such experience. I want that the page reload but without refreshing. End user should not feel that page is refreshing. Is it possible using simple html? or jquery?
I don't want <META HTTP-EQUIV="refresh" CONTENT="5"> or setTimeout of jquery because it refreshes the page while reloading?
Don't reload the whole page. Just use ajax to reload the components that needs to be updated. jQuery is perfect for that.
Use a setInterval with an ajax request. I'll update in 1 min with the script.
var divid = 'yourDivsId'
function createRequestObject()
{
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
obj = new ActiveXObject("Microsoft.XMLHTTP");
}else{
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(req)
{
http.open('get', req);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse()
{
if (http.readyState == 4)
{
var response = http.responseText;
document.getElementById(divid).innerHTML=response;
}
}
var http = createRequestObject();
setInterval('yourUrl', 30000); //or whatever time you want.
Should do the trick.

Categories