Chrome extension: Execute some code if a specific tab is not found - javascript

I am developing a chrome extension and after it is installed it iterates through opened tabs and if the required Tab is not found then I open a new tab. Following is my code:
var found = false;
chrome.tabs.getAllInWindow(null, function(tabs){
for (var i = 0; i < tabs.length; i++) {
var tabUrl = tabs[i].url;
if (tabUrl == 'http://www.youtube.com') {
chrome.tabs.update(tabs[i].id,{url:someUrl,selected:true});
found = true;
}
}
});
if (!found) {
window.open('https://www.youtube.com/watch?v=somevideid');
}
The problem is that whether the youtube is found or not the NOT FOUND if condition always return true and the default video URL is opened where as it should only open if youtube tab is not found. I think the Last if condition is not at the right place, any idea?

You should use chrome.tabs.query() instead of chrome.tabs.getAllInWindow(). The .query method, if called with an empty queryInfo object, will find ALL the tabs.
So, your code should be like this:
chrome.tabs.query({}, function(tabs) {
var found = false;
for (var i=0; i < tabs.length; i++) {
if (/https?:\/\/www\.youtube\.com/.test(tabs[i].url)) {
found = true;
chrome.tabs.update(tabs[i].id, {url: 'https://www.youtube.com/watch?v=somevideid', active: true});
break; // you found it, stop searching and update the tab
}
}
if (!found) chrome.tabs.create({url: 'https://www.youtube.com/watch?v=somevideid', active: true});
// you didn't find it, create a new tab with the new url and select it
});
Also, I used the regexp /https?:\/\/www\.youtube\.com/ to test the url of the tab, because the url may begin with "http" or "https", or may have some query string attached, like "?hl=en" or similars, so using tab[i].url == "http://www.youtube.com/" will not provide you absolute certainty of finding the tab.

Related

refersh the tabs that are opend in all windows(multiple window)in chrome

I am using a code to update/refresh all the tabs in all the browser, specifically same application opened in multiple browser. I need to refresh/ update the tabs in all multiple window.
var queryInfo = {
currentWindow:true
};
chrome.tabs.query(queryInfo, function (tabs) {
for(var i = 0; i < tabs.length; i++) {
chrome.tabs.update(tabs[i].id, {url: tabs[i].url});
}
});
If I give current window true current window tabs are updated if I give false other window tab is updated. I want to update tabs in all multiple window.
How can I do it?

chrome.tabs.update stops working when called from extension

I tried the following code. It basically takes a screenshot from all tabs open in the current window:
function captureWindowTabs(windowId, callbackWithDataUrlArray) {
var dataUrlArray = [];
// get all tabs in the window
chrome.windows.get(windowId, { populate: true }, function(windowObj) {
var tabArray = windowObj.tabs;
// find the tab selected at first
for(var i = 0; i < tabArray.length; ++i) {
if(tabArray[i].active) {
var currentTab = tabArray[i];
break;
}
}
// recursive function that captures the tab and switches to the next
var photoTab = function(i) {
chrome.tabs.update(tabArray[i].id, { active: true }, function() {
chrome.tabs.captureVisibleTab(windowId, { format: "png" }, function(dataUrl) {
// add data URL to array
dataUrlArray.push({ tabId:tabArray[i].id, dataUrl: dataUrl });
// switch to the next tab if there is one
if(tabArray[i+1]) {
photoTab(i+1);
}
else {
// if no more tabs, return to the original tab and fire callback
chrome.tabs.update(currentTab.id, { active: true }, function() {
callbackWithDataUrlArray(dataUrlArray);
});
}
});
});
};
photoTab(0);
});
}
When I call this code from popup.html opened as a webpage, it works as expected (I trigger this from a button click in the popup.html). When I call it from the browser extension, it just gets interrupted from the first tab it selects. Any idea why that is? I can't share errors, since the debugger gets closed when called from the extension.
Supplementary, is there a way to achieve desired result without needing the visual tab switching?
While updating the next tab as active tab. make sure current tab is no more active tab by doing
chrome.tabs.update(tabArray[i-1].id, { active: false }, ()=>{});
Moving the extension to a background script fixed the problem.
Reasoning is that the popup will close once the tab switches. Hence it is required to run in the background where it is not interrupted when the popup closes.

Chrome extensions close all tabs without certain div

i'm having a lot of trouble with Chrome Extensions, im trying to close all open tabs that do not contain a certain class.
This is the general idea of what i am trying to do, some of it is pseudo-code.
//background.js
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.query(function(tabs) {
chrome.tabs.sendMessage(tabs, {"message": "clicked_browser_action"});
});
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
for (var i = 0; i < request.length; i++) {
var existsClass = request[i].getElementByClass("someClass");
if (existClass === null) {
//TODO Close tab
}
}
}
}
);
Any help or suggestions would be appreciated.
Thanks!
I'm assuming your second snippet is from a content script.
In that case, it's as simple as window.close(), because you're in that tab's context. No need for Chrome APIs.
Try this:
//background.js
chrome.browserAction.onClicked.addListener(function () { //when the extension's icon is pressed
chrome.tabs.query({},function(tabs) { // get all tabs
for (var i = tabs.length; i--;){ // loop through all tabs
chrome.tabs.executeScript(tabs[i].id,{code: //execute this code in each tab
"if (!document.querySelector(\".someClass\")) close();"});
// ^ if no element is found with the selected class, close the tab
}
});
});
You don't need a separate content script for that.

Linking Directly To An Open Modal Window Through a URL?

I don't know much at all about coding so hopefully i worded the question correctly.
What I am trying to do is link a person to a specific modal window on another website. In this example, I will use the Menards weekly ad to show what I would like to do.
I would like to link somebody directly to the weekly flyer page with the modal window already open for a specific product such as the $74.99 5 Shelf Unit, which when selected opens this window (http://i.imgur.com/lntNUpK.png). This is the window that I would like to directly link to somebody.
Is there a way to modify the URL to make this possible? About all I know how to do is how to link to a specific page of the URL which would look like this /main/flyer.html?page=5
One other thing to mention is if you go to the website that provides the ads, Flipp, it does allow you to directly link to the window https://flipp.com/item/175356457-muscle-rack-5shelf-steel-unit
Thanks for any help!
Yes it is possible with some javascript, it will look for #myModal on the url if it finds it, it will load the modal:
just put this at the end of your page:
$(document).ready(function() {
if(window.location.href.indexOf('#myModal') != -1) {
$('#myModal').modal('show');
}
});
Now just use the following url:
http://www.mywebsite.com/page.html#myModal
*your modal must have an id:
<div class="modal" id="myModal">
How about that?
function openModalOnHash() {
if(window.location.hash) {
var hash = window.location.hash.substring(1);
$('#'+hash).modal('show');
}
}
$(document).ready(function() {
openModalOnHash()
});
I believe this should work. Only opens modal (if modal exist) with specified ID in URL
$(document).ready(() => {
const href = window.location.href
const modalID = href.split('/').reverse()[0]
if(modalID){
$(modalID).modal('show')
}
})
Yes, you can catch get param on url , https://www.exampleurl.com/?param=ModalIdShow
// Start Page
$(function(){
var param = GetURLParameter('param');
if(param == 'ModalIdShow'){
$("#ModalIdShow").modal("show");
}
});
//Catch param
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}

Forcing all open instances of a web-page to refresh in a Google Chrome web-application

I've been trying to make a JavaScript function for a Google Chrome web-application that checks to see if there are any open instances of the application, and if there are, forces them to refresh the page.
My original code is as follows:
chrome.tabs.getAllInWindow(undefined, function(tabs) {
for (var i = 0, tab; tab = tabs[i]; i++) {
if (tab.url == "chrome-extension://" + chrome.i18n.getMessage("##extension_id") + "/html/application.html") {
chrome.tabs.update(tab.id, {url: "chrome-extension://" + chrome.i18n.getMessage("##extension_id") + "/html/application.html"});
}
}
});
But this only works for all tabs inside the current window. If there are instances in their own window or in another window, they will not be refreshed.
I adapted it in an attempt to make it work for all open pages, and not just those in the currently selected window like so:
chrome.windows.getAll({populate: true}, function(tabs) {
for (var i = 0, tab; tab = tabs[i]; i++) {
if (tab.url == "chrome-extension://" + chrome.i18n.getMessage("##extension_id") + "/html/application.html") {
chrome.tabs.update(tab.id, {url: "chrome-extension://" + chrome.i18n.getMessage("##extension_id") + "/html/application.html"});
}
}
});
While the new code does not return an error in the JavaScript console, it does not seem to do what it is supposed to do; refresh any open instances of the application page.
Have I misunderstood the windows.getAll module? Can anybody offer a working solution?
chrome.windows.getAll returns an array of windows, not tabs. Each window contain an array of tabs. I don't remember right now how tabs array is called, I am assuming it is tabs (just dump returned windows into console and check):
chrome.windows.getAll({populate: true}, function(windows) {
console.log(windows);
for (var w = 0; w < windows.length; w++) {
for (var i = 0; i < windows[w].tabs.length; i++) {
var tab = windows[w].tabs[i];
if (tab.url == "chrome-extension://" + chrome.i18n.getMessage("##extension_id") + "/html/application.html") {
chrome.tabs.update(tab.id, {url: "chrome-extension://" + chrome.i18n.getMessage("##extension_id") + "/html/application.html"});
}
}
}
});
Instead of iterating all tabs, you can just iterate your "own" extensions opened pages:
var views = chrome.extension.getViews();
for (var i in views) {
var location = views[i].location;
if (location.pathname == '/html/application.html') {
location.reload();
}
}
The above should work, cleaner, and faster than iterating all windows.
For other searching Google, this code may be of interest to you. I used it to refresh a browser action icon on the active tab of each window, so when the extension updates or reloads, the icon has a status present:
chrome.tabs.query({active: true}, function queryCallback(tabs){
var length = tabs.length;
for (var i = 0; i < length; i++) {
handleTab(tabs[i]);
}
});

Categories