Opening multiple sites on the browser tabs with window.open - javascript

I have the following code and need to open two new tabs pointing to 2 web sites. For example: www.google.com and www.yahoo.com
It works only if I put one site in there
window.open("https://www.google.com");
but not when both lines
window.open("https://www.google.com");
window.open("https://www.yahoo.com");
Can you tell me what i need to do to be able to open both sites?
(function() {
document.getElementById("btnAsync").addEventListener('click', makeRequest);
function makeRequest() {
var httpRequest = new XMLHttpRequest(); // Initiatlization of XMLHttpRequest
if (!httpRequest) {
alert(' Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
};
window.open("https://www.google.com");
window.open("https://www.yahoo.com");
}
})();
<button id="btnAsync" type="button">Click Me</button>

I run your code. Both sites opened. But before it opens browser blocked popup window so i had to allow it to open. Try your code. And dont forget to allow popup after pressing button.

In the bad old days, it was common for malicious websites to fork bomb browsers by triggering an infinite loop of new windows.
They implemented protection against this by allowing new windows (and tabs) to be opened only when the function was triggered by a user event (e.g. a click but not a page load) and restricting this to opening a single window.
Some browsers may prompt the user to allow an additional window to open, but there is no way for a website to simply bypass this important security feature.

Related

Why browser refresh and close event detection is not working for IE and Safari

I need to call logout function on the close of browser window gets close. It's working fine in Chrome not working in IE and Safari.
I have tried the following code:
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here
var evtobj = window.event ? event : e;
if (evtobj == e) {
//firefox
if (!evtobj.clientY) {
//server call
}
}
else {
//IE
if (evtobj.clientY < 0) {
//server call
}
}
//return "Please click 'Stay on this Page' and we will give you candy";
};
I have tried a few other ways but they didn't work. Please advise.
There is something wrong in your design, you SHOULDN'T rely on a client-side hook to perform logout. There are one billion of reasons why that event could not be executed. Just limit the onbeforeunload event to execute informational content and not critical actions.
By the way:
Don't return in your beforeunload event! This creates some issue in IE
Use window.sessionStorage to make some data last until the user closes the tab
Use session cookies to store your user's sensitive data like as tokens, and check if a user is logged on the server, and not on the client

Check if still connected to host with Javascript

In some place there is a policy which needs user to click button Continue to enter for example music streaming website.
Let's assume I want to use this website for a time longer than this policy accepts. After some period of time the music stops playing and after refreshing webpage - policy asks you for clicking Continue again, even if you have not left the page.
I'd like to make a script which would check if a connection still persists, but without website refreshing (because it plays music).
I've already created script which would click Continue, but don't know how to (and if it is possible) check connection, if connection is broken then refresh website and click Continue.
Can it be done with GreaseMonkey?
I enter http://deezer.com/
Script click Continue for me
I listen to music
Script is checking connection
if connection is ok go to 3.
Refresh website
Go to 2.
Click script:
if (document.title == 'Click continue')
{
var a = document.getElementById('continue-text');
a.children[1].click();
}
If no policy then the return of page is:
200 OK 318ms
If policy goes on, then it returns:
200 Forbidden 91ms
You can check the connection like this:
function checkConnection() {
var xmlhttp;
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 == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
// this might need some customisation:
var connected = document.getElementById("id_of_the_continue_button") ? true : false;
if (!connected) {
reconnect();
}
}
else {
reconnect();
}
}
}
// here you'll need a relevant url:
xmlhttp.open("GET", "http://deezer.com/", true);
xmlhttp.send();
}

Is there a way to tell if a browser is active?

On my site I have an important notification that prompts a native alert() in order to bring the site to the foreground if the window is not already focused. The problem is that on some browsers, if the user is in another desktop application (Photoshop, Microsoft Word, etc), it will not bring the browser on top of that application. In this case the alert is pretty much useless and I would like to omit it (since it blocks the other scripts on my page).
Is there a way to tell that a browser is the active application on a device? Or is there a different, non-blocking way to bring a window to the foreground?
Thanks!
Clarifications:
I already know how to check if a window is active within a browser, but I just don't know how to check if the browser application itself is active.
Also, browsers I need to support are Chrome, Safari, Firefox, and IE >= 9
You can use the Page Visibility API for this.
It is compatible with IE 10+.
Small example of code:
document.addEventListener("visibilitychange", function(e) {
console.log("visibility changed!", e);
if (document.visibilityState === 'visible') {
console.info("window is visible now!");
}
else {
console.info("something else, maybe you changed tab or minimized window!");
}
console.log("check the visibilityState property on document object for more info");
});
This will work even if the user minimizes the browser while the tab is open, so I guess this suits your needs :)
You should use the new Notification object. It works even when the browser is not focused, and is useful for sending the user important notifications.
Example: http://jsfiddle.net/howderek/792km8td/
document.getElementById('notif').onclick = function () {
function notify () {
var notification = new Notification('Test!');
}
if (Notification.permission === "granted") {
setTimeout(notify, 5000);
} else {
Notification.requestPermission(function () {
if (Notification.permission === "granted") {
setTimeout(notify, 5000);
}
});
}
}
https://developer.mozilla.org/en-US/docs/Web/API/notification
Have a global variable storing whether the window is active or not:
var window_active = true;
Now add event listeners to "listen" for window (de)activation:
window.onblur = function () {
window_active = false;
};
window.onfocus = function () {
window_active = true;
};
And when you call the alert function, check that global variable:
if (window_active)
alert("notification");
I want to mention that if you change the tab or click the url-bar, the window will be deactivated, which might be not what you want.

XMLHttpRequest from Firefox Extension

I'm using XMLHttpRequest to exchange data between server and Firefox extension I'm developing. Unfortunately, those requests seem somehow connected with the currently open page - if I try to issue request while the current tab is closing, it will fail with an error. How can I make my requests originate from the extension itself, independently of what's going on in tabs?
EDIT: Here is the code that reproduces this problem. It's run as the main extension body (I based my design on the "Hello world" tutorial from http://kb.mozillazine.org/Getting_started_with_extension_development, so no Add-on SDK). This means that it's executed in the same place as the code from "overlay.js" in above tutorial.
function createXMLHttpRequest() {
return Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
}
function issueRequest() {
var req = createXMLHttpRequest();
req.open("GET", "http://google.com", true);
req.addEventListener("load", function(event) {
alert("SUCCES");
});
req.addEventListener("error", function(event) {
alert("ERROR");
});
req.send();
};
window.addEventListener("DOMContentLoaded", function(event) {
issueRequest();
var doc = event.originalTarget;
var win = doc.defaultView;
win.addEventListener("unload", function(event) {
issueRequest();
});
});
This results in "SUCCESS" after opening of new tab, and "ERROR" after closing it. I would prefer to have two SUCCESSES.
If that script is running in a browser window overlay then you attached your DOMContentLoaded handler to the wrong node - you will only get notified when the browser window itself loads. Consequently, your unload handler waits for the browser window to the closed, you probably intended to wait for a tab to be closed. The correct code would look like this:
// Wait for the browser window to load before doing anything
window.addEventListener("load", function() {
// Attach a listener to the tabbrowser to get notified about new pages
window.gBrowser.addEventListener("DOMContentLoaded", function(event) {
issueRequest();
var doc = event.originalTarget;
var win = doc.defaultView;
win.addEventListener("unload", function(event) {
issueRequest();
});
}, false);
}, false)

Opening my page in firefox after installing the addon

HI,
My am trying to open my home page after the firefox restarts for the first time after installation.
For this i am adding the event handler on load page and checks where this event is executed for the first time or not.
window.addEventListener("load", initializeOverlay, false);
But my problem is how to open the page in new tab when the firefox get started. I use
`window.open("https://www.xyz.com/");`
but that opens the page in new window that might even be open in internet explorer.
So is there any way to open the page in new tab in same window which is going to be open.
Thanks
BHAVIK GOYAL
I manage to do something similar using preferences, rather than creating files, etc.
Inside of /defaults/preferences/default.js:
pref("extensions.extension_name.just_installed", true);
pref("extensions.extension_name.post_install_url", "http://www.google.com");
Then inside the main JS file for the add-on:
// Retrieve the preferences.
var prefs;
prefs = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.extension_name.");
prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
// If we just installed, open the post-install page and update the preferences.
var just_installed = prefs.getBoolPref("just_installed");
var post_install_url = prefs.getCharPref("post_install_url");
if (just_installed) {
prefs.setBoolPref("just_installed", false);
gBrowser.selectedTab = gBrowser.addTab(prefs.getCharPref("post_install_url"));
}
Only problem is Firefox doesn't reset the preferences saved by an extension after that extension is uninstalled.
I got the answer. We can add the gbrowser.open("http://www.xyz.com/") to open in new tab and this statement has to be executed in new function that is by calling the other event handler function loadedoverlay which is defined as follow:
function loadedOverlay() {
try{
var file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(Components.classes["#mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile).path+"\\initialstart.txt");
if ( file.exists() == true )
{
}
else
{
file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
var Website="http://www.emailstationery.com/";
gBrowser.addTab(Website);//This is for new Tab
}
} catch(e) {}
}
The call to this function has to be add in the load event function by adding the code of lines as below:-
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", loadedOverlay, true);

Categories

Resources