javascript window.open from callback - javascript

window.open() called from main thread opens new tab by default.
But, here open new window every time (Opera 16 and Google Chrome 29)
<input type="button" value="Open" onclick="cb1()">
<script type="text/javascript">
function cb1() {
setTimeout(wo, 1000); //simple async
}
function wo()
{
var a = window.open("http://google.com", "w2");
a.focus();
}
</script>
(lol, this is my answer for Open a URL in a new tab (and not a new window) using JavaScript).
How I can open in the tab (by browser default) here?

We ran across this same problem and hunted around SO for an answer. What we found works in our circumstances and the distilled wisdom is as follows:
The problem is related to browser pop-up blockers preventing programmatic window opens. Browsers allow window opens from actual user clicks which occur on the main thread. Similarly, if you call window.open on the main thread it will work, as noted above. According to this answer on Open a URL in a new tab (and not a new window) using JavaScript if you are using an Ajax call and want to open the window on success you need to set async: false which works because that will keep everything on the main thread.
We couldn't control our Ajax call like that, but found another solution that works because of the same reasons. Warning, it is a bit hacky and may not be appropriate for you given your constraints. Courtesy of a comment on a different answer on Open a URL in a new tab (and not a new window) using JavaScript you open the window before calling setTimeout and then update it in the delayed function. There are a couple of ways of doing this. Either keep a reference to the window when you open it, w = window.open... and set w.location or open with a target, window.open('', 'target_name'), in the delayed function open in that target, window.open('your-url', 'target_name'), and rely on the browser keeping the reference.
Of course, if the user has their settings to open links in a new window this isn't going to change that, but that wasn't a problem for the OP.

Like the other posts mentions the best way to do this is to first open the window and then set its location after the callback or asynchronous function
<input type="button" value="Open" onclick="cb1()">
<script type="text/javascript">
function cb1() {
var w = window.open('', 'w2');
setTimeout(function () {
wo(w);
}, 1000); //simple async
}
function wo(w)
{
w.location = "http://google.com";
w.focus();
}
</script>
Alternatively if you are using async await you will also have the same problem. The same solution still applies.
public async openWindow(): Promise<void> {
const w = window.open('', '_blank');
const url = await getUrlAsync();
w.location = url;
}
A further enhancement is to open the window on an initial page that provides some quick feedback either by loading a url or writing some html to that page
public async openWindow(): Promise<void> {
const w = window.open('', '_blank');
w.document.write("<html><head></head><body>Please wait while we redirect you</body></html>");
w.document.close();
const url = await getUrlAsync();
w.location = url;
}
This will prevent a user looking at a blank tab/window for however long it takes to resolve your URL.

This is even 'hackier' but...
If you wrap the window.open in a console.log then it will work.
console.log(window.open('https://someurl', '_blank'))

If a new window is opened as a new tab, or a new instance, depends on the user-settings.

I was working with Nestjs and Vue3. but I solved it using this code write here.
I just took the token that was sent from the back end on the localhost:8080.
So I just slice the token and set it local storage then redirect the user to the next page. which will authorize the user to use this token.
Vue 3.
This way is solved. you can improve it and make it even better.
that's how I did it because I used the OAuth google-passport in the backend instead of firebase
<script>
methods: {
googleLogin() {
const win = window.open(
"http://localhost:3000",
"windowname1",
"width=800, height=600"
);
const validateToken = (token) => {
localStorage.setItem("token", token);
this.$router.push("/GeneralPage");
window.clearInterval(pollTimer);
clearInterval(pollTimer);
win.close();
};
const pollTimer = window.setInterval(async () => {
try {
let url = win.document.URL;
let token = url.slice(22, url.length);
if (token !== "") {
localStorage.setItem("token", token);
this.$router.push("/GeneralPage");
clearInterval(pollTimer);
win.close();
validateToken(token);
return;
}
return;
} catch (e) {}
}, 1000);
},
}
</script>

Related

Is there a way to detect if the browser has a mailto protocol handler set?

I have a site that dynamically builds a mailto url which it then opens in a new tab/window, using window.open().
window.open("mailto:" + encodeURIComponent(r["to"]));
I'm testing in Chrome at this stage, so other browsers may act differently.
If Chrome has a mailto protocol handler set up (e.g. GMail), then it works as expected.
If Chrome does not have a mailto protocol handler set up, it just opens a tab with the mailto url and nothing else.
That's not the worst result, but it would be nice if there was a way of knowing in advance, so that the user could be in some way guided to setting up their browser so that the mailto url worked nicely.
Previously, I was just opening in the same page by setting window.location.href to the url:
windows.location.href = "mailto:" + encodeURIComponent(r["to"]);
This wasn't great because if there was no protocol handler set, nothing happened. I also would consider this as an option, IF I can at least detect the situation, but wasn't able to find any indication of that either. I guess one option would be to set a timer which if it reached execution could alert the user?
Anyone else already solved this? Seems like a pretty common requirement.
Thanks
Here's what I ended up working with. It doesn't work in all cases, but provides at least some help in recognising unhandled protocols.
It attempts to open the URL in a new window and then after 2s it takes a look to see if it can read the location. If it has opened a third party site (e.g. GMail) this will raise and exception - so we treat this as success.
If no exception occurs, this returns "about:blank" which means we (probably) failed.
function openWin(url) {
return new Promise((resolve, reject) => {
const w = window.open(url);
if (!w) {
reject();
}
setTimeout(function() {
try {
const working = w.document.location.href;
} catch (e) {
resolve();
return;
}
w.close();
reject();
}, 2000);
});
}
Called with something like this:
openWin('mailto:' + encodeURIComponent(to)).then(() => {
// handle success
}).catch(() => {
// handle failure
});
Caveat: This only works for web-based protocol handlers. If for example your mailto is handled by an email app, then this will fail.
In my case, most people would be using web-based email, so it works for most cases. On failure I show a message to the affect of "If your email didn't open, copy the email address here..."

Problems with Testcafe LocalStorage

everyone!
I'm new to TestCafe and I need some help on something I want to achieve.
I have a React website where I put a Facebook Login. Normally, when you enter the page and click on Login with facebook a popup window opens and enter your credentials normally. After that, you are redirected to the page and the token is saved in a localStorage variable for the page to consult later on.
However, when I run test for login process, Testcafe instead of opening a popup window, opens the facebook form on the same page and never redirects to the page.
Also, I tried to set some dummy token on the localstorage using the ClientFunction (and also Roles) and my website can never reach that token because testcafe seems to put this variable on a key called hammerhead
So, my question here is, how could I enter this token on the test or manually so my website can read it and make some functions with it?
This is what I have so far.
/* global test, fixture */
import { WelcomePage } from './pages/welcome-page'
import {ClientFunction, Role} from 'testcafe';
const welcomePage = new WelcomePage()
const setLocalStorageItem = ClientFunction((prop, value) => {
localStorage.setItem(prop, value);
});
const facebookAccUser = Role(`https//mypage.net/`, async t => {
await setLocalStorageItem('token', 'my-token');
}, { preserveUrl: true });
fixture`Check certain elements`.page(`https//mypage.net/`)
test('Check element is there', async (t) => {
await t
.navigateTo(`https//mypage.net/`)
.wait(4000)
.useRole(facebookAccUser)
.expect(cetainElementIfLoggedIn)
.eql(certainValue)
.wait(10000)
})
Any help would be highly appreciated
Thanks for your time.
UPDATE FROM FEB 2021
TestCafe now supports multiple browser windows and you can log-in via the Facebook popup form without any issues. Refer to the Multiple Browser Windows topic for more information.
Currently, TestCafe does not support multiple browser windows. So it's impossible to log in via the Facebook popup form.
However, there is a workaround. Please refer to the following thread https://github.com/DevExpress/testcafe-hammerhead/issues/1428.
My working test look like this:
import { Selector, ClientFunction } from 'testcafe';
const patchAuth = ClientFunction(() => {
window['op' + 'en'] = function (url) {
var iframe = document.createElement('iframe');
iframe.style.position = 'fixed';
iframe.style.left = '200px';
iframe.style.top = '150px';
iframe.style.width = '400px';
iframe.style.height = '300px';
iframe.style['z-index'] = '99999999';
iframe.src = url;
iframe.id = 'auth-iframe';
document.body.appendChild(iframe);
};
});
fixture `fixture`
.page `https://www.soudfa.com/signup`;
test('test', async t => {
await patchAuth();
await t
.click('button.facebook')
.switchToIframe('#auth-iframe')
.typeText('#email', '****')
.typeText('#pass', '****')
.click('#u_0_0')
.wait(30e3);
});
Please keep in mind that manipulations with x-frame-options in the testcafe-hammerhead module are required.
In addition, I would like to mention that Testing in Multiple browser windows is one of our priority tasks, which is a part of TestCafe Roadmap

Open new browser window

I am new to javascript and I am using the code below to open a browser window and do some things. However, when I open multiple files simultaneously, it just opens a new tab in the existing browser window, but I want it to open in a new window (preferably incognito mode if possible). Based on my research, I'm thinking I can just modify the if statement, but I'm not sure how.
<html>
<body onload="window.setTimeout('document.getElementById(\'criimlaunch\').click();', 1000);">
<script>
var macroCode = '';
macroCode += 'PROMPT HELLO!\n';
function launchMacro()
{
try
{
if(!/^(?:chrome|https?|file)/.test(location))
{
alert('iMacros: Open webpage to run a macro.');
return;
}
var macro = {};
macro.source = macroCode;
macro.name = 'EmbeddedMacro';
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent('iMacrosRunMacro', true, true, macro);
window.dispatchEvent(evt);
}
catch(e)
{
alert('iMacros Bookmarklet error: '+e.toString());
};
}
</script>
<a id="criimlaunch" href="javascript:launchMacro();">Launch iMacros</a>
</body>
</html>
If you want to open new window you should use
window.open (URL, windowName[, windowFeatures])
I think below links will help you.
Using the window.open method
window.open w3schools
Chrome extensions with the tabs permission can use the chrome.windows.create method:
chrome.windows.create({"url": url, "incognito": true});
However, to access it, you'll either need to write your own extension or find an existing one which provides a suitable hook
You can try
windows.create({"url": url, "incognito": true});

Implementing Dropbox API V2 in Cordova Application

I have a Cordova application with previous Dropbox implementation using rossmartin/phonegap-dropbox-sync-android. Now as the API V1 is going to be deprecated I want to upgrade to Dropbox API V2. I have searched for plugins for Cordova applications using Dropbox API V2 but didn't find any.So I am trying to implement it using dropbox/dropbox-sdk-js.
For Authentication, I am using authenticateWithCordova method which returns me the Access token (Full documentation here).This method returns Access token once the user completes authentication with Dropbox and uses the redirect URL to redirect the user to Cordova application.
This method works perfectly when the user clicks the button for the first time, but when the user clicks the button again calling this method shows a blank screen and return a new access token. How to avoid seeing the blank screen?
This is the method from Dropbox-sdk.js file, which I have called from my application,
DropboxBase.prototype.authenticateWithCordova = function (successCallback, errorCallback)
{
var redirect_url = 'https://www.dropbox.com/1/oauth2/redirect_receiver';
var url = this.getAuthenticationUrl(redirect_url);
var browser = window.open(url, '_blank');
var removed = false;
var onLoadError = function(event) {
// Try to avoid a browser crash on browser.close().
window.setTimeout(function() { browser.close() }, 10);
errorCallback();
}
var onLoadStop = function(event) {
var error_label = '&error=';
var error_index = event.url.indexOf(error_label);
if (error_index > -1) {
// Try to avoid a browser crash on browser.close().
window.setTimeout(function() { browser.close() }, 10);
errorCallback();
} else {
var access_token_label = '#access_token=';
var access_token_index = event.url.indexOf(access_token_label);
var token_type_index = event.url.indexOf('&token_type=');
if (access_token_index > -1) {
access_token_index += access_token_label.length;
// Try to avoid a browser crash on browser.close().
window.setTimeout(function() { browser.close() }, 10);
var access_token = event.url.substring(access_token_index, token_type_index);
successCallback(access_token);
}
}
};
Here is my code which I use to call the method,
function authenticateWithCordova()
{
var dbx = new Dropbox({ clientId: CLIENT_ID });
dbx.authenticateWithCordova(AuthSuccess,AuthFail);
}
function AuthSuccess(accessToken)
{
localStorage.accessToken = accessToken;
}
function AuthFail()
{
alert("Auth Fail");
}
I have found an analog issue right yesterday. This is the way I solved it.
First, I have set var dbx as global. In my index.js I put these lines immediately after app.initialize():
var CLIENT_ID = 'xxxxxxxxxxxxxxx';
var dbxt;
var dbx = new Dropbox({clientId: CLIENT_ID});
Then I check if dbxt is null: if it is, I create a new Dropbox object using accessToken, otherwise I go with the dropbox connection already established:
if (dbxt == null) {
dbx.authenticateWithCordova(function (accessToken) {
dbxt = new Dropbox({accessToken: accessToken});
dbxt.filesUpload({
path: '/mydump.sql',
contents: sql,
mode: 'overwrite',
mute: true
}).then(function (response) {
alert('Your backup has been successfully uploaded to your Dropbox!')
}).catch(function (error) {
alert('Error saving file to your Dropbox!')
console.error(error);
});
}, function (e){
console.log("failed Dropbox authentication");
}
}else{//dbxt already created
dbxt.filesUpload... //and the rest
}
This is just to avoid to create a new connection and get a new access token everytime and I confess I'm not sure this is a good practice: I only know that before to apply this code I got a lot of bad requests responses by Dropbox server:)
When I used the above code, after the first login, I started to see the blank page: that's is the inappbrowser page which Dropbox OAuth2 uses as redirect URI (set to https://www.dropbox.com/1/oauth2/redirect_receiver in your Dropbox app page).
So the problem was how to make this page invisible. I found a dirty trick applying a small tweak to inappbrowser.js script.
Near the bottom of the script, immediately before this line:
strWindowFeatures = strWindowFeatures || "";
I have put this small block:
if (strUrl.indexOf('dropbox') > -1){
strWindowFeatures += "location=no,hidden=yes";
}
I would have expected to can just use 'hidden=yes' but surprisingly if I remoce 'location=no' the blkank page appears again.
Notice 1: you don't have to modify the script inappbrowser.js located at plugins\cordova-plugin-inappbrowser\www\ but the one you find in platforms\android\platform_www\plugins\cordova-plugin-inappbrowser\www\
Notice 2: I have found this workaround right now so I'm not 100% sure it works perfectly.
Notice 3: making the inappbrowser page invisible, depending on the Internet connection, it could look like nothing is happening for a while, so you'll have to add some loader to inform your user that the app is working.
Hope this help.
UPDATE
I've just realized we can tweak directly the dropbox-sdk instead of inappbrowser.
If you are using Dropbox with browserify you have to open dropbox-base.js and look for authenticateWithCordova() method (it should be at line 107. Then change the line
var browser = window.open(url, '_blank');
to
var browser = window.open(url, '_blank', "location=no,hidden=yes");
If you are using Dropbox-sdk.min.js, you have to look for 'window.open' using the search function of your code editor. It will be easy because 'window.open' is used only once. So you'll have to change the following:
i=window.open(n,"_blank"),
to
i=window.open(n,"_blank","location=no,hidden=yes"),
And this seems to work fine (I prefer to be careful before I get excited).
UPDATE 2
Forgive previous update. My previous check:
if (strUrl.indexOf('dropbox') > -1){
strWindowFeatures += "location=no,hidden=yes";
}
is wrong because it makes invisible any inappbrowser window which tries to connect to dropbox so it prevent us from even logging into Dropbox. So we need to change it to
if (strUrl == 'https://www.dropbox.com/1/oauth2/redirect_receiver') {
strWindowFeatures += "location=no,hidden=yes";
}
This way we can do the login correctly and next connections won't show the inappbrowser window, as we want.
So summarizing:
Ignore my first update
Use UPDATE 2 to modify the url check in inappbrowser.js
Forgive me for the confusion...

How to determine which Tab in Firefox Browser is about to make a http request

I'm currently trying to build a firefox extension that determines a proxy for each http request based on Regular Expressions. The Proxy that has been used for loading a page should be remembered for any new request coming from that page, ie. any image/script/css file needed for that page, any outgoing links or ajax requests. That also means that the proxy needs to be remembered for each open tab.
This is where I run into my problem: Up until now I tried to mark each open tab by inserting a unique id as an attribute of the browser element of the tab, and looking for this id in an implementation of the shouldLoad() method of nsiContentPolicy. The code I'm using for this is shown below, and it was extracted from the addon sdk's getTabForContentWindow method in tabs/utils.js.
shouldLoad: function(contentType, contentLocation, requestOrigin, context, mimeTypeGuess, extra)
{
var tabId = null;
if (!(context instanceof CI.nsIDOMWindow))
{
// If this is an element, get the corresponding document
if (context instanceof CI.nsIDOMNode && context.ownerDocument)
context = context.ownerDocument;
// Now we should have a document, get its window
if (context instanceof CI.nsIDOMDocument)
context = context.defaultView;
else
context = null;
}
let browser;
try {
browser = context.QueryInterface(CI.nsIInterfaceRequestor)
.getInterface(CI.nsIWebNavigation)
.QueryInterface(CI.nsIDocShell)
.chromeEventHandler;
} catch(e) {
this.console.log(e);
}
let chromeWindow = browser.ownerDocument.defaultView;
if ('gBrowser' in chromeWindow && chromeWindow.gBrowser &&
'browsers' in chromeWindow.gBrowser) {
let browsers = chromeWindow.gBrowser.browsers;
let i = browsers.indexOf(browser);
if (i !== -1)
tabId = chromeWindow.gBrowser.tabs[i].getAttribute("PMsMark");
}
return CI.nsIContentPolicy.ACCEPT;
}
This works fine for any load that does not change the displayed document, but as soon as the document is changed(ie. a new page is loaded), the variable browser is null.
I have looked at the other mechanisms for intercepting page loads described on https://developer.mozilla.org/en-US/Add-ons/Overlay_Extensions/XUL_School/Intercepting_Page_Loads , but those seem to be unsuitable for what I want to achieve, because as far as I understand they work on HTTP requests, and for a request to exist, the proxy already needed to be determined.
So, if anybody knows a way to catch imminent loads before they become requests, and at the same time, it's possible to find out which tab is responsible for those loads-to-be, I'd be glad if they could let me know in the answers! Thanks in advance!
https://developer.mozilla.org/en-US/docs/Code_snippets/Tabbed_browser#Getting_the_browser_that_fires_the_http-on-modify-request_notification
Components.utils.import('resource://gre/modules/Services.jsm');
Services.obs.addObserver(httpObs, 'http-on-opening-request', false);
//Services.obs.removeObserver(httpObs, 'http-on-modify-request'); //uncomment this line, or run this line when you want to remove the observer
var httpObs = {
observe: function (aSubject, aTopic, aData) {
if (aTopic == 'http-on-opening-request') {
/*start - do not edit here*/
var oHttp = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel); //i used nsIHttpChannel but i guess you can use nsIChannel, im not sure why though
var interfaceRequestor = oHttp.notificationCallbacks.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
//var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below
var loadContext;
try {
loadContext = interfaceRequestor.getInterface(Components.interfaces.nsILoadContext);
} catch (ex) {
try {
loadContext = aSubject.loadGroup.notificationCallbacks.getInterface(Components.interfaces.nsILoadContext);
//in ff26 aSubject.loadGroup.notificationCallbacks was null for me, i couldnt find a situation where it wasnt null, but whenever this was null, and i knew a loadContext is supposed to be there, i found that "interfaceRequestor.getInterface(Components.interfaces.nsILoadContext);" worked fine, so im thinking in ff26 it doesnt use aSubject.loadGroup.notificationCallbacks anymore, but im not sure
} catch (ex2) {
loadContext = null;
//this is a problem i dont know why it would get here
}
}
/*end do not edit here*/
/*start - do all your edits below here*/
var url = oHttp.URI.spec; //can get url without needing loadContext
if (loadContext) {
var contentWindow = loadContext.associatedWindow; //this is the HTML window of the page that just loaded
//aDOMWindow this is the firefox window holding the tab
var aDOMWindow = contentWindow.top.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem).rootTreeItem.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow);
var gBrowser = aDOMWindow.gBrowser; //this is the gBrowser object of the firefox window this tab is in
var aTab = gBrowser._getTabForContentWindow(contentWindow.top); //this is the clickable tab xul element, the one found in the tab strip of the firefox window, aTab.linkedBrowser is same as browser var above //can stylize tab like aTab.style.backgroundColor = 'blue'; //can stylize the tab like aTab.style.fontColor = 'red';
var browser = aTab.linkedBrowser; //this is the browser within the tab //this is what the example in the previous section gives
//end getting other useful stuff
} else {
Components.utils.reportError('EXCEPTION: Load Context Not Found!!');
//this is likely no big deal as the channel proably has no associated window, ie: the channel was loading some resource. but if its an ajax call you may end up here
}
}
}
};

Categories