Close window with JavaScript background script? (Firefox Extension) - javascript

I am currently writing a Firefox extension that opens a new window in my background script. When a user clicks a button on a page the background script executes and opens the window.
So far I have:
// content script
downloadMod(linkToOpen); //button clicked
function downloadMod(url) {
// var test = window.open(url, '_blank');
var myPort = browser.runtime.connect({ name: "cac410c4672fff93bf0d3186636d8876de3dfeb6#temporary-addon"});
myPort.postMessage({ greeting: url });
}
In my background script (the script the above code connects too) I have:
//background script
portFromCS.onMessage.addListener(function (m) {
var test = browser.windows.create({
url: m.greeting,
allowScriptsToClose: true,
});
NOTE: all the code works as expected. However, the trouble comes when closing the window.
I have tried variations of self.close(), window.close(). I even created a function to wait 5 seconds to load the newly created window and then close the page to no avail. All of my attempts come back with the error:
Scripts may not close windows that were not opened by script.
I thought this error was supposed to be removed with the allowScriptsToClose flag?

To close a window you created with browser.windows.create, you need to use browser.windows.remove.
So:
let windowId;
browser.windows.create({url: "http://google.be"}).then((data) => {
windowId = data.id;
});
// Sometime later, use windowId to close the window
setTimeout(function(){
browser.windows.remove(windowId);
}, 5000);

Related

How to return focus on parent window from a pop window while loading first time

I am working on a website. Where while loading website first time opening index page with one pop window. First my problem is I want to minimize this pop window automatically while loading first time and focus return to website without any click in website.
Here is my code in index page I write this function:
myFunction();
function myFunction() {
//var myWindow = window.open("music.php", "", "width=320,height=60");
var myWindow = window.open("music.php", "", "directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no,left=-100000000, top=100000, width=320, height=1, display=none","visibility=hidden");
//myWindow.moveTo(0, 0);
}
And pop window having page extension music.php which should be minimize automatically and focus return to index page without any click on website.
I have already try with set the focus of a popup window to website everytime , but it was also not working.
Well, The window object has an opener property as well.
When we open the browser, that property is null, and when we open a popup , it points to the window the popup has been opened through.
I think something like this should suffice.
myFunction();
function myFunction() {
var myWindow = window.open("music.php", "", "directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no,left=-100000000, top=100000, width=320, height=1, display=none","visibility=hidden");
myWindow.opener.focus() // can also do window.focus()
}
The execution of JS should not stop, but if it does, you have to add the focus code to your child page/popup page.(Depending on varying browsers)
like
popupHTMLJS.js
focusParent();
function focusParent(){
parent = window.opener;
parent.focus()
}

window.open(url).print() not working in Safari

I have an issue while printing in the Safari browser. When I use window.open(url) and try to print this newly opened URL, it tries to print a blank page.
As suggested in few other sites, I tried to set a delay of 3000ms. Like,
window.open(url)
setTimeout(print, 3000);
This tries to print the previous window and not the new tab open.
I have tried using window.focus() before printing. It didn't help.
First, the Window object passed in the setTimeout is the one from the original page, so you should do something like
var popup = window.open(url);
popup.onload= function(){
// this now refers to `popup`
this.print()
}
But since you mentioned a Safari issue, I'll note that this seems to only work for normal document page (at least for HTML files) in this browser.
For documents like data:image/..., the Window object returned by window.open() doesn't have any property (at least in bugged Safari 9.1 on 10.9, didn't tried in other versions), hence you can't call the popup.print() method.
One way for it would be to create yourself the page and e.g for an image, append an <img> tag with the desired url as src.
It will depend on what you are trying to print though.
var url = 'data:image/png;base64,...';
// you have to keep a reference of the new Window
var popup = window.open(url);
var tryToPrint = function() {
// we have access to the window methods
if (popup.print) {
// call directly its print method
popup.print()
} else {
// close this one
popup.close();
// open a new blank one
popup = window.open('');
// create an image
var img = popup.document.createElement('img');
// reproduce default Safari's styles
img.setAttribute('style', '-webkit-user-select:none; display:block; margin:auto;');
// once the image has loaded, we can print the page
img.onload = function() {
popup.print()
};
popup.document.body.appendChild(img);
img.src = url;
}
};
// unfortunately, we can't even listen to the load event of the bugged popup
// so come back to an ugly timeout...
setTimeout(tryToPrint, 200);
Live Demo

Firefox Add-On SDK: Run content script in new tab only once

I am trying to develop a simple add-on for Firefox which should work something like this:
User clicks item in context menu.
New tab is opened.
Content (innerHTML) of the new tab is overridden using content script.
Also, the content script should only be executed once, so that if the user would enter a website in the new tab the script should not be executed.
I've got it working with editing the new tabs content, but my only problem is to have the content script run only once when the tab is opened. In the code I have at the moment the script run every time a page has been loaded in the tab:
var contextMenu = require("sdk/context-menu");
var tabs = require("sdk/tabs");
var menuItem = contextMenu.Item({
label: "Test",
contentScript: 'self.on("click", function () { self.postMessage(); })',
onMessage: function (data) {
newTab();
}
});
function newTab () {
tabs.open("about:blank");
tabs.activeTab.on('ready', function (tab) {
tab.attach({
contentScript: 'document.body.innerHTML = "testing";'
});
});
}
I'm guessing there's a way to have this run only the first time the tab is "ready". Seems like a simple task but I can't figure out how to do this. Anyone got any tips?
Use tabs.activeTab.once(); instead of tabs.activeTab.on();.
This way the listener gets detached once it intercepts the first message.

I need to reload current location js

I need to reload current location(href) via JS :
I have a button that open a new window and when that window closed I need to reload the location in window that was initiator(parent). It is work in my browser, but one said me that his window does not reload( he has last version chrome and mac book)
I have the followin code:
var loginWindow = window.open(...);
loginWindow.focus();
loginWindow.onbeforeunload = function() {
location.reload(); //when the popUp window close
//I even tried this:
window.location.href = window.location.href;
}
but the page not reloaded
AS onbeforeunload does not work here it is recommended to check if the window exists with certain interval Please find the reference link below
Check this post

How to open a mailto: link from a Chrome Extension?

I have a URL shortening Chrome extension called Shrtr. Right now, it allows users to copy the shortened URL to clipboard, but in the next version, I've added the ability to email the shortened URL, using a mailto: link (i.e. mailto:?subject=<original page title>&body=<short URL>).
The problem is, you cannot just assign document.location.href = 'mailto...'; from an extension. The following 2 methods worked for me, but with both, I end up with an open blank tab in the browser:
Method 1: window.open
var wnd = window.open(emailUrl);
setTimeOut(function() {
wnd.close();
}, 500);
Notice the need to wait before closing the window. This works (i.e. mail client new message dialog appears, pre-populated), but the new tab remains open.
Method 2: using chrome.tabs
chrome.tabs.create({ url: emailUrl }, function(tab) {
setTimeOut(function() {
chrome.tabs.remove(tab.id);
}, 500);
});
Again, works - but tab remains open. Any ideas?
var emailUrl = "mailto:blah#blah.com";
chrome.tabs.update({
url: emailUrl
});
I realize this is an old question, but I myself had the same issue, and I figured out how to solve the problem so I thought I would share.
The issue stems from the fact that (I believe) you are calling the below code from your extension popup page.
chrome.tabs.create({ url: emailUrl }, function(tab) {
setTimeout(function() {
chrome.tabs.remove(tab.id);
}, 500);
});
The problem with this is that as soon as a new tab is created, the popup page dies and the callback code is never executed.
We can remedy this by moving that code into a function within the background page whose lifetime is not tied to the popup page:
function sendEmail() {
var emailUrl = "mailto:blah#blah.com";
chrome.tabs.create({ url: emailUrl }, function(tab) {
setTimeout(function() {
chrome.tabs.remove(tab.id);
}, 500);
});
}
and calling it via chrome.extension.getBackgroundPage().sendEmail() from your popup page.
Using the above method, the default email client will be opened, and the new tab will be automatically closed after 500 milliseconds.
wouldnt u need a close statement like this
close
credits go to Daniel How to close current tab in a browser window?
or even something like this
//keep a handle to the window you open.
var newWin = window.open('my window', 'http://.../');
...
//some point later in the code
newWin.close();
credits go to Tracker1 Javascript Code to close tab that works in IE, Firefox and Chrome?
I have solved the problem. Please check if it fits your solution space.
I have used the following code to open a mailto client in chrome extension.
$('.email').click(function(){
var hrefString = $(this).attr('href');
var myWindow = window.open(hrefString, "Opening mail client", "width=200, height=100");
myWindow.document.write("<p>Opening mail client.Please wait!!</p>");
setTimeout(function(){ myWindow.close() }, 2000);
});
where the element was :
<a style="padding: 0 0 0 5px;" href="mailto:abc#xyz.com" class="email">
This worked for me.
Hope it will help others.
Regards,
Karan Ratra

Categories