How to go to a specific tab with Firefox Extension - javascript

I'm creating a Firefox Extension. It opens a new tab and then closes it a moment later. When the new tab closes, I want to go back to the original tab I was on, NOT the rightmost tab. This is what I have so far and it always goes to the rightmost.
function openNewTab(tabs) {
let tab = tabs[0];
browser.tabs.create({"url": tab.url});
}
function closeTab(tabs) {
let tab = tabs[0];
browser.tabs.remove(tab.id);
}
function onError(err){
console.error(err);
}
function openAndClose() {
var mytab = browser.tabs.query({currentWindow: true, active: true}).then(openNewTab, onError);
setTimeout(function () {
var closeIt = browser.tabs.query({currentWindow: true, active: true}).then(closeTab, onError);
}, 1000);
}
browser.browserAction.onClicked.addListener(openAndClose);
Given a tab id, or tab index, how do I activate, or go to that specific tab?

You want the window & tab update functions. You can disregard focusing the window as long as you keep focus of the window when you create your new tab. (As currently shown in your code sample)
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/windows/update
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/update
browser.tabs.query({}, function(tabs) {
for (var i=tabs.length-1; i>=0; i--) {
if (tabs[i].id == myTabID) {
browser.windows.update(tabs[i].windowId, {focused: true}); //focus window
browser.tabs.update(tabs[i].id, {active: true}); //focus tab
break;
}
}
});

Related

Closing browser tabs with Protractor?

I've tried the advice offered in this post How to close the current tab of the browser in protractor with out closing the complete browser to close the new browser tab in Chrome and return to the main application. The first one is ignored; the second results in errors.
I also tried the browser.actions().keyDown(protractor.Key.CONTROL).sendKeys('w').perform();
which I found elsewhere.
browser.switchTo().window(secondWindowHandle)
.then(function () {
browser.ignoreSynchronization = false;
empLogin.test();
}).then(function(){
browser.close(); //close the current browser
}).then(function(){
browser.switchTo().window(firstWindowHandle) //Switch to previous tab
.then(function(){
//Perform your operations on the first tab
});
});
First function moves to first tab, second goes back to previous and closes the second:
var moveToTab = function() {
browser.driver.sleep(5000).then(function() {
browser.getAllWindowHandles().then(function(handles) {
newWindowHandle = handles[1]; // this is your new tab
browser.switchTo().window(newWindowHandle);
});
});
};
var goBackToPreviousTab = function() {
browser.getAllWindowHandles().then(function(handles) {
previousWindowHandle = handles[0]; // this is your previous tab
browser.switchTo().window(previousWindowHandle);
});
}

Is there a way to set focus to parent tab on opening a child tab?

The following code sets focus on the new tab, not to the opener.
function openChildtab() {
var win = window.open("https://www.amazon.co.uk/gp/product/B01J90O0N4/ref=sv_kinc_2", "_blank");
if (win) {
window.focus();
} else {
alert("Please allow popups for this website");
}
}
Open New tab

Chrome Capturing Visible Tab not working

The code in buttonClicked() function and onTabCreate() function worked when the button is the BrowserAction icon.
But when I added a popup.html and created few buttons in it. When "Trello" button is clicked. I want the code in buttonClicked() to be executed, I put this code in eventPage.js.
The control is reaching the function, but I'm unable to capture the visible Tab now.
Why is it so? How can I fix this?
As evident from the code, imageData is holding the image of the tab (3rd line in buttonClicked())
The last 4th line in buttonClicked(), calls onTabCreate(). InonTabCreate(), I'm passing the imageData, but I'm not receiving the image.
I'll furnish more info if needed.
Thanks
buttonClicked()-
function buttonClicked() {
chrome.tabs.captureVisibleTab(null, {}, function (image) {
imageData = image;
createdTabUrl = chrome.extension.getURL('cardCreate.html');
chrome.tabs.query({ active: true }, function (tabs) {
var i, tab;
// Only select the current active tab, not any background tab or dev tools
for (i = 0; i < tabs.length; i += 1) {
// TODO: more robust way to check if current tab is a page from this extension (either when I get a static extension id or with a flag)
if (tabs[i].url.match(/^http/) || tabs[i].url.match(/^chrome-extension.*\/cardCreate\.html$/)) {
tab = tabs[i];
}
}
chrome.tabs.create({ url: createdTabUrl, index: (tab.index || 0) + 1 }, onTabCreated);
});
});
}
onTabCreate()-
// TODO: more robust way to send image data to page ?
function onTabCreated(tab) {
setTimeout(function (){
chrome.runtime.sendMessage({ imageData: imageData }, function(response) {
// Callback does nothing
});
}, 1000);
var views = chrome.extension.getViews();
for (var i = 0; i < views.length; i++) {
var view = views[i];
// If this view has the right URL and hasn't been used yet...
if (view.location.href == createdTabUrl) {
console.log("----------------------");
// console.log(view);
// console.log(view.location.href);
}
}
}
chrome.browserAction.onClicked.addListener(buttonClicked);
EDIT :
window.onload = function() {
document.getElementById('loginText').addEventListener('click', login);
document.getElementById('Trello').addEventListener('click', buttonClicked);
//listener for ButtonClick
// In popup.html , I included eventPage.js as well.
};

Change Active Window (chrome.tabs)

I've made an extension for pandora.com and when the user clicks the extension icon it opens a new tab with pandora.
When pandora is already open in a new tab and the user clicks the extension, the extension will not open a new tab but I would like it to instead change the active tab to the tab with pandora already open.
This is what I have so far in my background page:
chrome.browserAction.onClicked.addListener(function(tab) {
var found = false;
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.search("pandora.com") > -1){
found= true;
}
}
if (found==false){
chrome.tabs.executeScript(null,{file: "buy.js"});
} else {
// Changes active tab to the tab with pandora open
}
});
});
UPDATE- chrome.tabs.update(tabId, {selected: true}); achieves what I needed. Here's the final code:
chrome.browserAction.onClicked.addListener(function(tab) {
var found = false;
var tabId;
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.search("www.pandora.com/") > -1){
found = true;
tabId = tabs[i].id;
}
}
if (found == false){
chrome.tabs.executeScript(null,{file: "buy.js"});
} else {
chrome.tabs.update(tabId, {selected: true});
}
});
});
Seems like the selected property of the second argument of chrome.tabs.update has now been deprecated.
Using the active property is the new way to do it:
chrome.tabs.update(tabId, {active: true})
If the tab to be activated is in another window, you also need to change the active window to that window using chrome.windows.update:
chrome.windows.update(windowId, {focused: true}, (window) => {
chrome.tabs.update(tabId, {active: true})
})

New tab/window links in Safari with a redirect of the current page

So I have this script here, it's main purpose is to open a specified link in a new tab/window and THEN redirect the current window (where the script has been fired, not the new tab).
It works as follow. You specify a link to listen on it for a click event, once it's clicked two instructions should fire up. New tab should be opened and the current window should be redirected.
The problem is that this script works in chrome, but in safari this script results just in a redirect to the specified url, the new tab/window does't not open up.
function openTab(url) {
// Create link in memory
var a = window.document.createElement("a");
a.target = '_blank';
a.href = url;
// Dispatch fake click
var e = window.document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
var aNode = document.getElementsByTagName('a'),
/* this is current link's url, just click copy link address you want to affect, and paste it here between ''*/
/* it supports multiple buttons with different links */
currentUrl = ['https://www.google.com/intl/en/ads/'],
/*this link loads in new tab */
newTabUrl = 'http://www.google.com/',
/* this link loads after the 'newTabUrl' is opened */
redirectUrl = 'http://www.youtube.com/';
for (var t = 0; currentUrl["length"] > t; t++) {
for (i in aNode) {
if (aNode[i].href && aNode[i].href == currentUrl[t]) {
aNode[i].href = redirectUrl; // without this the page will be not redirected in chrome (second instruction in the addEventListener, function below does not fire up somehow...)
aNode[i].addEventListener('click', function(){
openTab(newTabUrl);
window.location = redirectUrl;
console.log('fired'); //debugging
});
console.log('affected!'); //debugging
}
console.log(i); //debugging
}
}

Categories

Resources