Open new browser window - javascript

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});

Related

How to focus on opened popup window from a new tab using JavaScript

I have a URL, which is working with JavaScript. When I am hitting that URL then it will open a new window popup(window.open()) and again when I am hitting the same URL from a new tab and on the same browser, It is opening a new window popup even previous popup window is already opened.
So, Is there any way to focus on an already opened popup window instead of opening a new popup window from the new tab on the same browser?
(Un)Fortunately, there seems to be no reliable way to bring a window or tab into focus (see here or here).
For your other issue (not opening a new popup if it is already open), you have some options based on cross window/tab communication (assuming same origin):
You can set a cookie in your popup and delete it once the popup is closed (or more specifically unloaded). When attempting to open a new popup, check whether the cookie is already set. This has some pitfalls like you not having control over how many times the popup is opened by the user (manually, without your guard).
You can implement a form of tab/window communication (summarized in this question).
Assuming you can modify the popup and they share the same origin, an implementation based on Broadcast Channels might look like this (just to give you an idea):
From the source:
const bc = new BroadcastChannel('channel_id');
let isPopupOpen = false;
bc.onmessage = (ev) => {
if (ev.data === 'popup-id-exists') {
isPopupOpen = true;
}
};
function openPopup() {
isPopupOpen = false;
bc.postMessage('popup-id');
setTimeout(() => { if (!isPopupOpen) window.open('popup.html') }, 100);
}
From the popup:
const bc = new BroadcastChannel('channel_id');
bc.onmessage = (ev) => {
if (ev.data === 'popup-id') {
bc.postMessage('popup-id-exists');
}
};

The if/else in background script does not execute on extension click but only after unpacked extension refresh

I'm trying to load a background script (extension-starter.js) that contains an if/else statement. I store a user's preference for how to open the extension (popup, new window, new tab) in local storage. Upon opening the extension, I expect it to retrieve the saved value and open the extension appropriately, but for some reason when changing the preference (for example from popup to new tab), clicking the extension icon opens the extension in the previous state. Only after I refresh the unpacked extension does it open the app as expected.
// Here is the manifest.json...(took out unnecessary info)
{
"manifest_version": 2,
"background": {
"persistent": false,
"scripts": ["extension-starter.js"]
},
"browser_action": {}
}
// Here is the extension-starter.js...
const extPrefer = localStorage.getItem('extensionPreference');
if (extPrefer === null) {
localStorage.setItem('extensionPreference', 'popup');
}
chrome.browserAction.onClicked.addListener(function () {
if (extPrefer === 'window') {
chrome.windows.create({url: chrome.runtime.getURL("index.html"), width: 500, height: 600});
}
else if (extPrefer === 'tab') {
chrome.tabs.create({url:chrome.extension.getURL("index.html")});
}
else {
chrome.browserAction.setPopup({
popup: "index.html"
});
}
})
I expect to retrieve the saved preference from local storage and open the extension in the desired manner.
UPDATE
The above issue is caused by chrome.browserAction.setPopup({popup: "index.html"});. Once the setPopup is executed, I cannot update back to window or tab preference. It seems like setPopup is being set on the manifest and cannot be overwritten when changing the preference from popup to tab or window.
Updated Question:
1. Is there a way to do the opposite of setPopup?
2. Is there another method for setPopup?
Please try this a tell me how it goes:
if (localStorage.getItem('extensionPreference') === null) {
localStorage.setItem('extensionPreference', 'popup');
}
chrome.browserAction.onClicked.addListener(function () {
// move this inside the click function
const extPrefer = localStorage.getItem('extensionPreference');
if (extPrefer === 'window') {
chrome.windows.create({ url: chrome.runtime.getURL("index.html"), width: 500, height: 600 });
}
else if (extPrefer === 'tab') {
chrome.tabs.create({ url: chrome.extension.getURL("index.html") });
}
else {
chrome.browserAction.setPopup({
popup: "index.html"
});
}
})
Okay, I figured it out! Below I will explain the ultimate issue and then, the solution.
Issue
In the background script, I wanted to allow a saved value in localStorage to determine whether the extension opens as a popup, a new window, or a new tab. Switching between window and tab worked, except when switching from popup. If popup is selected, the extension would open as a popup. When switching to new tab, for example, the extension would still open as a popup. The new value would only work after restarting the extension. The issue was in, drumroll please:
chrome.browserAction.setPopup({popup: "index.html"});.
Solution
I am not sure as to the exact cause of the issue above (and I don't want to just say things that may be false or not 100% accurate) but the simple solution was executing the setPopup method on a tab rather than the browser.
First, in the chrome.browserAction.onClicked.addListener method's callback function pass in tab.
chrome.browserAction.onClicked.addListener(function (tab) {
Second, set the setPopup to execute on the tab by doing the following...
chrome.browserAction.setPopup({tabId: tab.id, popup: "index.html"});
The above solution works like a charm. If anything is not clear, please let me know! Thanks JamesWasson for helping!

How to run function on new tab from main tab? (Google Chrome)

I need to open console and run one function on new tab, that I opened using javascrip. The opening part is easy, but how to run function on other tab?
var google = window.open("http://google.com")
Upon reading your question, it seems you're looking to open the dev console for the popup? Assuming this is what you're looking for, you should just be able to right-click the popped-up window and hit 'Inspect Element'. Then go to the console from there.
If you're trying to programatically run a function from the parent onto the popup window, here's an idea for you.
Assuming the new window is on the same domain as yours, this solution may work for you. (browser support is limited)
On the parent page:
//store the function in localStorage
localStorage.runThis = function(){ alert("Hello world"); }
//open the popup window
newWindow = window.open("http://your-domain.com/your-page");
On the page to open in the popup:
//check if the function has been stored
if(typeof localStorage.runThis === "function"){
//run the function in localStorage
localStorage.runThis();
}
One issue is that this method relies on this criteria being met:
Browser supports localStorage
Parent page and Popup page come from the same origin
Popup page must actually look for the function in question and execute the function itself
One drawback of this is that if someone were to go to the Javascript Console and set their own function into localStorage, the popup page would see their function and run potentially dangerous code - a security hole.
A common solution is using localstorage.
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
localStorage.setItem("lastname", "Smith");
var lastname = localStorage.getItem("lastname");
} else {
// Sorry! No Web Storage support..
}

using a redirect to launch an app and still stay in same page in asp.net

I have written a website that uses bankid authentication, I don't know how common this is outside of sweden, but basically it is either an app in the mobile phone, or a local software in windows. to launch the application in windows a redirect needs to be made that looks like this:
if (startLocalApp)
{
Response.Redirect("bankid:///?autostarttoken=" + AuthResp.AuthenticateResponse1.AutoStartToken + "&redirect=" + Request.Url.AbsoluteUri);
}
the problem with this though is that the redirect of the software does not work the way I need it to work since the redirect it does opens a new tab with the web page I need to get back to in a new tab, and the session variable is all messed up. so what I need to do is the opposite, launch the app in a new tab, and let it close the tab when it's done, since I have all references needed before I've launched the app it does not need to be executed in the same browser window even.
so how to make the redirect in another tab, and is it possible to keep executing code after the redirect? if not, I need to make a post back to continue execution of the code-behind.
edit:
I've tried one solution, it feels like I'm getting closer but I'm not quite there yet.
front-end:
<script type="text/javascript">
function StartBankIdApp(){
var _url = 'bankid:///?autostarttoken=<%= (AuthResp == null || AuthResp.AuthenticateResponse1 == null) ? "null" : AuthResp.AuthenticateResponse1.AutoStartToken %>&redirect=null';
var $irWin = window.open(_url, '_blank');
if ($irWin != null) {
$irWin.close();
}
}
</script>
code-behind:
if (startLocalApp)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), StartBankIdApp", "StartBankIdApp()", true);
}
the app is not launched, i.e the window it should open does not open.
did I do something wrong?
I think you are trying to use "URL scheme" to launch an app. And that you want that the app should be triggered in a new tab (or window).
This can be achieved through javascript. To open any link in new tab we can use window.open and set target attribute as _blank. Here is a sample code
var _url = 'app:MyApp?queryString=somestring';
var $irWin = window.open(_url, '_blank');
if ($irWin != null) {
$irWin.close();
}
What I've done here is that after launching the app I've closed the new tab (or window).
The javaScript code would continue to run (that is it will not wait for the app to complete the process).

javascript window.open from callback

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>

Categories