Switch chrome tabs and refresh every 5 seconds - javascript - 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);
});

Related

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.

execute script only one time until next refresh

I am building a chrome extension and i am executing a action on the extension icon
chrome.browserAction.onClicked.addListener(function(tab) {
triggerTab(tab);
});
var alreadyClicked = false,ct='';
function triggerTab(tab) {
if (!alreadyClicked || ct != tab.url) {
addMachine(tab);
}
ct = tab.url;
alreadyClicked = true;
}
By this code its only execute script once forever on current tab..
I want to run script only once on a tab until next refresh .
how about adding an eventlistener to onUpdated event?
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
alreadyClicked = false;
});

Chrome.runtime.onMessage.addListener on new tab not receiving message from popup.js

I have the following code in popup.js which responds to a button press to get all the tabs, create a new tab (template.html), and send the tabs as an array to the new tab. Later I will delete the current tabs and display the links on one page to save space (That's the idea of the extension).
function saveAll() {
var openTabs = [];
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; i++) {
openTabs[i] = tabs[i];
}
createSavedPage(openTabs);
});
}
function createSavedPage(tabsToSave) {
chrome.tabs.create({
"url": chrome.extension.getURL("template.html"),
"active": false
},
function(tab) {
sendListToPage(tab, tabsToSave);
}
);
}
function sendListToPage(tab, tabsArray) {
chrome.tabs.sendMessage(tab.id, {
"action": "fill-list",
"data": tabsArray
});
}
var saveAllButton = document.getElementById("select-all-tabs");
saveAllButton.addEventListener("click", saveAll);
The tab that is created includes a template.js file:
function fillList(array) {
var list = document.getElementById("link-list");
for (var item in array) {
//Something
}
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.action == "fill-list") {
var data = request.data;
fillList(data);
}
}
);
When I create the new tab, the message is sent from the extension but never received. What is causing this issue?
I also thought that the message was being sent before the created tab was fully loaded. So I've changed popup.js by adding a chrome.tabs.onUpdated listener:
function createSavedPage(tabsToSave) {
chrome.tabs.create({
"url": chrome.extension.getURL("template.html"),
"active": false
},
function(tab) {
chrome.tabs.onUpdated.addListener(function(tabId, info) {
if (tabId == tab.id && info.status == "complete")
sendListToPage(tab, tabsToSave);
});
}
);
}
And it seems to solve the issue. Is there still a better way?

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

Categories

Resources