Closing Tab in Chrome Extension - javascript

I have a function called in popup.html that creates a tab, inserts a mailto to trigger a local (or gmail) mail event. It's my desire for it to then close itself. I've tried numerous things, but it seems like I need something that does the equivalent of:
tabId = chrome.tabs.query(I DON'T KNOW!);
chrome.tabs.remove(tabId);
here's the current code:
var query = { active: true, currentWindow: true };
function callback(tabs) {
var currentTab = tabs[0];
console.log(currentTab);
}
chrome.tabs.remove(chrome.tabs.query(query, callback));
but it's not working.
if useful, here's how I create the tab (which does work as desired):
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
getTabs(tabs, function(full_mail_link){
chrome.tabs.create({ url: full_mail_link });
});
});
any help would be greatly appreciated!

I don't know what your getTabs function does. Yet if you know how to find the tab id of the tab you want all you need to do is
chrome.tabs.remove(tabId, optionalCallback);

this must be work:
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.remove(tab.id);
});

This should work:
//create the tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
getTabs(tabs, function(full_mail_link){
chrome.tabs.create({ url: full_mail_link }, callBackOnCreate);
});
});
function callBackOnCreate(tab)
{
globalCreatedTab = tab.id;
}
chrome.tabs.query({'active': true}, function(tabs) {
for (var i = 0; i < tabs.length; ++i)
{
if (tabs[i].id === globalCreatedTab)
{
chrome.tabs.remove(tabs[i].id, [optional callback]);
}
}
});
Solution: use the query function with the callback and execute the remove function in the callback.
It looks like normal window.open and window.close() should also work,
The tab-id is an integer or an array containing integers.

Related

How to go to a specific tab with Firefox Extension

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

"chrome.tabs.query" can't Execution my code

function onWindowLoad() {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
tabUrl = tabs[0].url;
alert(tabUrl);//taburl is Successfully displayed in my browser
$("#txtUrl").val(tabUrl);//This line of code is not implemented
alert("hello");//cant't alert hello
});
window.onload = onWindowLoad;
please help me :I want to get the url to my page, but after running the code and nothing happens,How to deal with it?

Switch chrome tabs and refresh every 5 seconds - javascript

I'm trying to build a chrome extension using the Chrome tabs API that will cycle through all of the open tabs in a window and refresh each one every n seconds. I'm having trouble iterating my for loop once every 5 seconds. I've tried a few different ways of setting timeouts and such but I'm either ending up with the loop not running at all, or I get an infinite loop. I'm new to javascript. Any help would be appreciated!
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
// Send a message to the active tab
chrome.tabs.query({currentWindow: true}, function(tabs) {
var foundSelected = false;
(function switch() {
for(i = 0; i <= tabs.length; i++){
if(i == tabs.length){
i = 0;
}
if (tabs[i].active){
foundSelected = true;
}
// Finding the next tab
else if (foundSelected){
// Selecting the next tab.
chrome.tabs.update(tabs[i].id, {active: true});
chrome.tabs.reload(tabs[i].id);
setTimeout(switch, 5000);
}
}
})();
// var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
});
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
chrome.tabs.update(tabId, {selected: true});
}
}
);
I realize that there are already extensions out there that do this. I'm creating my own as a learning experience and for more control over functionality.
Create background.js like given below. I thnik it will work properly.
background.js
/* Below code start background.js when you start your browser
* and sw function work after every 5 second and reload every tab.
*/
function sw()
{
chrome.tabs.query({currentWindow: true},function(tabs){
var i=0;
console.log(tabs.length);
for(i=0;i<=tabs.length;i++)
{
chrome.tabs.reload(tabs[i].id);
}
})
};
setInterval(sw,5000);
This is the working solution.
chrome.browserAction.onClicked.addListener(function(tab) {
setInterval(function () {
chrome.tabs.query({currentWindow: true}, function(tabs) {
var foundSelected = false;
for(var i = 0; i <= tabs.length; i++){
if(i == tabs.length){
i = 0;
}
if (tabs[i].active){
foundSelected = true;
}
// Finding the next tab.
else if (foundSelected){
// Selecting the next tab.
chrome.tabs.update(tabs[i].id, {active: true});
chrome.tabs.reload(tabs[i].id);
return;
}
}
});
}, 5000);
});

how to get background.js to change based on options.js

I am currently making a Google Chrome extension, and in the options I want the user to be able to choose between it being always on or only activating when clicked. To do this, I need an options.js and a background.js file, which I have. However, I am having a lot of trouble getting them to communicate properly. I tried using the chrome.storage api, but it won't do anything.
Here is my code for background.js:
chrome.browserAction.onClicked.addListener(function() {
// Send a message to the active tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {"message": tabs[0].url}, function(response));
});
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
// console.log(tabs.length);
chrome.tabs.sendMessage(tabs[0].id, {"message": tabs[0].url}, function(response) {});
});
}
});
And here is my code for options.js:
// Saves options to chrome.storage
function save_options() {
var behavior = document.getElementById('behavior').value;
chrome.storage.sync.set({
extensionBehavior: behavior
}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Options saved!';
setTimeout(function() {
status.textContent = '';
}, 1000);
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
// Use default value color = 'red' and likesColor = true.
chrome.storage.sync.get({
extensionBehavior: 'onClick'
}, function(items) {
document.getElementById('behavior').value = items.extensionBehavior;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
save_options);
If the behavior is set to "onClick", I only want the chrome.browserAction.onClicked.addListener portion to be executed. If the behavior is set to 'alwaysOn', then I only want the chrome.tabs.onUpdated.addListener portion to be executed. As far as debugging goes, both of those chunks work the way they're supposed to. I just need to know how to get one or the other to run based on the current options.
For the communication between option and background, it would be quite easy when you choose the localStorage to pass info between them. http://www.w3schools.com/html/html5_webstorage.asp

Refresh after a timer of 5000 seconds and print the alert

I am making a chrome extension to keep refreshing a page unless stop button is chosen. But i am able to do it only once. Here is my code for background.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
switch(request.type) {
case "table-row-count_start":
alert("Refershing started");
RefreshAndCount();
break;
case "table-row-count_stop":
alert("Stop Refershing");
break;
}
return true;
});
var RefreshAndCount = function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type: "table-row-count"});
chrome.browserAction.setBadgeText({tabId: tabs[0].id, text: "Counting!"});
});
};
In content.js I did this :
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
alert(message.type);
switch(message.type) {
case "table-row-count":
var x = document.querySelector('table').rows.length;
chrome.storage.sync.set({'value': x}, function() {
console.log('Settings saved');
});
chrome.storage.sync.get(["value"], function(items){
console.log(items);
});
alert("Row count = " + x);
setTimeout(function(){
location.reload();
},100);
break;
}
});
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (key in changes) {
if(key=='value'){
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
}
});
After refresh I want to print the current row count alert everytime. Please help how to do this .
This work fine, for a single refresh but after that I again had to choose the start button from popup.
I want some way that I need not click start button again and the whole process repeats, storing the previous row count in cache or something.
popup.js
window.onload = function() {
document.getElementById("mystartbutton").onclick = function() {
chrome.extension.sendMessage({
type: "table-row-count_start"
});
}
document.getElementById("mystopbutton").onclick = function() {
chrome.extension.sendMessage({
type: "table-row-count_stop"
});
}
}
Also help me How to keep on refershing that page even if I switch to other tab or minimise my chrome ?
You can use the chrome.storage.local to store data that will be saved over time and over context where you use it. You can set a boolean to true or false to enable or disable autoreload. Then you only have to set it at click on browser action and check it in the content-script to know if you have to reload.
A possible and simple implemtation should be like this : (It depends of the expected behavior)
content.js (have to be injected in the page to autoreload)
var reloadDuration = 5000;
function autoreload()
{
chrome.local.storage.get("autoreload_enabled", function(result)
{
if(result.autoreload_enabled)
{
chrome.runtime.sendMessage({type: "table-row-count"});
window.location.reload();
}
}
}
setTimeout(autoreload, reloadDuration);
This will reload your page every reloadDuration if the boolean set in chrome local storage named autoreload_enabled is true.

Categories

Resources