I've written a Chrome extension that overrides the New Tab page:
manifest.json:
"chrome_url_overrides": {
"newtab": "new-tab.html"
},
Is there a way to make this override optional? That is, I'd like to enable the user to uncheck a checkbox in the options page and disable the New Tab override. This must be possible because when I open a new tab for the first time, there's a popup informing of an extension changing the New Tab settings and asking whether to keep changes or restore settings:
I couldn't find any API for controlling overrides. The New Tab Redirect project doesn't have an option to display the native New Tab.
Google made a Star Wars new tab replacement which allows you to view the default new tab page. The url it uses is chrome-search://local-ntp/local-ntp.html.
Example:
options.html:
<input type="checkbox"> Use default new tab page
options.js:
var checkbox = document.querySelector("input[type=checkbox]")
checkbox.addEventListener("click", function() {
chrome.storage.sync.set({ defaultnewtab: checkbox.checked })
})
newtab.js:
chrome.storage.sync.get("defaultnewtab", function(storage) {
if(storage.defaultnewtab) {
chrome.tabs.update({ url: "chrome-search://local-ntp/local-ntp.html" })
}
})
Instead of using the chrome_url_override you could write a listener that listens for when tabs update using the chrome.tabs.onUpdated.addListener(), then check if the url is chrome://newtab/ and if it is and the check box is ticked, then using chrome.tabs.update() relocate them to another page.
Using the Star Wars method as described #Daniel Herr, I did this, which is working well. Although feels a little hack-y.
I have an option being set in the popup.html whether the Extension is "on" or not.
First off, set the default new tab page using the Chrome defined method:
manifest.json
"chrome_url_overrides": {
"newtab": "newtab.html"
},
Then in your Extension's newtab.html call a new JavaScript file, newtab.js (or whatever).
I am also using jQuery, so my code uses that, but you can do this natively using DOMContentLoaded.
newtab.js
$(document).ready(function(){
// It takes a moment for the Chrome query/update so sometimes there is a flash of content
// Hiding the Body makes it look blank/white until either redirected or shown
$('body').hide();
var background = chrome.extension.getBackgroundPage();
var _app = background._app;
// App is OFF, show Default New Tab
if(!_app._on){
// Get the current Tab
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
var active = tabs[0].id;
// Set the URL to the Local-NTP (New Tab Page)
chrome.tabs.update(active, { url: "chrome-search://local-ntp/local-ntp.html" }, function() { });
});
// App is ON, show custom content
} else {
$('body').show();
}
});
Basically, the methodology is to update the Tab so that it is redirected to chrome-search://local-ntp/local-ntp.html which is the hard URL to the default Chrome NTP.
Since this is a Chrome internal URL -- the URL field still appears blank.
Related
I want to create an extension for automatically logging into my servers. So I created a background page to check the current URL and if it conforms to my URL regex, I'll display the page action icon. On click of the page action I'm opening a popup with some fields. I need to get the currently opened URL and fill it in one of the fields in the popup(like when we click the standard bookmark page action, the URL gets automatically filled in the popup that opens). How can I do something like this in chrome extensions? I tried Message Passing from the background page to the popup html but it is not working. Is it possible to send messages like that? Also I tried setting onload for the popup html file but i noticed that it is not triggering. Please suggest a suitable method to deal with this scenario.
Use chrome.tabs.query with the following parameters:
queryInfo object:
active: true - To get the active tab
lastFocusedWindow: true - To select the active window
callback function:
This function receives one argument: An array of matched tabs. Since only one window can be active, and one tab within this window, the array has only one element. This element is an object with the Tab signature.
Code snippet:
// Do NOT forget that the method is ASYNCHRONOUS
chrome.tabs.query({
active: true, // Select active tabs
lastFocusedWindow: true // In the current window
}, function(array_of_Tabs) {
// Since there can only be one active tab in one active window,
// the array has only one element
var tab = array_of_Tabs[0];
// Example:
var url = tab.url;
// ... do something with url variable
});
The activeTab permission is sufficient for this to work.
You can also use promises for a cleaner way of retrieving a tab:
getCurrentTab().then(function(tab){
// Do something w/tab
});
function getCurrentTab(){
return new Promise(function(resolve, reject){
chrome.tabs.query({
active: true, // Select active tabs
lastFocusedWindow: true // In the current window
}, function(tabs) {
resolve(tabs[0]);
});
});
}
I'm trying to make a chrome extension go to a predefined link on the currently open tab. I can't figure out how to do this. Any ideas?
Add the following code in the background.js, Which handles the click event on extension.
chrome.browserAction.onClicked.addListener(() => {
chrome.tabs.query({ active: true }, (tabs) => {
const tab = tabs[0];
chrome.tabs.update(tab.id, {
url: 'https://stackoverflow.com/questions/68945425/update-and-run-pre-defined-link-on-current-tab-chrome-extension',
});
});
});
Code Explanation
On-click on the extension, I fetch the active tab information using chrome.tabs.query API.
chrome.tabs.query will return an array of tabs.
Get the 0'th indexed tab from the array and update the URL as per your requirement using chrome.tabs.update API.
Reference
https://developer.chrome.com/docs/extensions/reference/tabs/#method-update
I have a javascript application that shows notifications regularly.
When a notification is clicked, I want it to focus on the tab/window that my application is currently running.
I can get that behavior working fine with this code:
var options = {
body: msg.body,
sticky: true,
icon : 'img/logo_quad.png',
tag: id,
renotify : true
};
var notification = new Notification(msg.title,options);
notification.onclick = function(){
window.focus();
};
However, if I have two tabs running this same application at once, when I click it, instead of focusing one of the two tabs it opens a new tab with the same URL.
Why is that happening and how can I prevent it?
Note: A chrome only solution is welcome, I don't care about other browsers
how can I reload specific browser tab content? I search for solution which can not be only in JQuery (I prefer it if there more solution).
I need this:
I have page with a lot of links on another's pages (format of links: http://domain_name.cz/?still_same_text=1_1_1_1_1_1386662409 ; another page has this link: http://domain_name.cz/?still_same_text=1_1_14_1_2_1387231396 etc. everyone links has same format only to 1st number). When I click first time on some link then I load new tab (for this text I say him simply "tab2") if I click again on another link then I reload this "tab2" (= I change url in this "tab2" from current to new => I load new conent in this tab).
Is there some way to do that?
I try solution from this topic but this not work for me and, I mean, I have difficult problem. And I look at solution in this topic, but this is another problem. There is 1 link but I can have more links and there are links in JS but I need generate them in PHP.
I've not done this before, but the question seems interesting. Therefore, if the answers you mentioned did not work then I would try the following concept, it may not be the best, but it's something.
1- Make a tracker on the server (properly in session) to keep track of the pages that the user has opened. So whenever the user open a page, make an ajax request sending the page url with a random generated id number to be stored and checked later. Each tab will get a different id.
2- Add a javascript listener in all pages that keep waiting for commands from the server. Depending on the server response, those listen will do the following:
Nothing -> in case the page is opened first time.
Close tab -> in case a new tab with same link is opened. So keep the new tab and close the old one. // Or close new one and refresh old one?
Update -> update server once tab is opened (directly when the page gets loaded) and just before they get closed, send the page url and current tab id to be check on the server.
Keep checking server, if a newer tab with same url is opened, then close current.
I'm not sure if this solution is suitable for you, so I will only write a pseudo code. If it's applicable, then later maybe can improve it a bit.
pseudo code php: tabControl.php
//session array structure
//when a new tab is added, it will take the following index of current url array. So later we can know which one is
//$_SESSION["tracker"][ current url ][ tab id] newer id will be added to the array in an ascending order, not based on their value, so later we can check which tabId came later.
$action = $_POST["action"];
$tabId = $_POST["id"];
$tabUrl = $_POST["url"];
if($action === "check")
{
processTab(tabUrl , $tabId);
}
elseif($action === "closing")
{
closeTab(tabUrl , $tabId) ;
}
/*if this a second tab opened with the same url, then echo the previous tab id and command the client to close self.
*if this the first tab, then store it in session.
*/
function processTab($tabUrl , $tabId)
{
//if new, then pass it to addTab
// else, check if there is a newer tab opened, then call closeTab
}
function addTab($tabUrl , $tabId)
{
// add a new tab associated with tabUrl -> couter -> tabId
}
function closeTab($tabUrl , $tabId)
{
//set that $tabUrl with the id to null.
//and ask the client to close the tab. //echo json_encode(array("responce"=>"closeSelf"))
}
And from the client side, you can use something similar to this pseudo code:
//current tab id
var tabId = Math.floor((Math.random()*100)+1);
//On exit, just run once before user close the tab/window.
$(window).unload(function(){
$.ajax({
type: 'POST',
url: 'tabControl.php',
async:false,
data: {"url":window.location.pathname , "action":"closing" , "id":tabId}
});
});
// keep checking periodically
function checkTabs()
{
//On load, just run once
$.ajax({
type: 'POST',
url: 'tabControl.php',
data: {"url":window.location.pathname , "action":"check", "id":tabId},
type:"json",
success:function(data)
{
if(data.responce === "closeSelf")
{// if the user detected that there is a newer with this url opened.
window.close();
}
}
}).always(function(){ setTimeout(checkTabs, 1000);});
}
checkTabs();// to call for the first time.
Hope this helps.
In fact, this isn't a difficult problem if you use appropriate technology. Controlling specific browser tabs can be done with the browser SDK, which has access to the tab management. JavaScript or PHP themselves cannot access a specific tab because it would be a security breach.
Example for Google Chrome:
Take a look at the chrome.tabs reference. There is many things you can do with tabs including what you are trying to do. For example, a user-friendly way of displaying a link that can control browser tabs would be to use a browser popup (attention, this isn't the same thing as a conventional popup, a browser popup is an "internal" browser-level popup that is suggesting that this specific area may control any part of the browser instead of the current page only) that contains the links. In that popup, you could have something like this:
Browser popup (HTML):
<a id="myLink" href="http://wwww.google.com">This link will control a new tab</a>
Browser popup (JavaScript):
var tabNumber;
var tabCreated = false;
document.getElementById("myLink").addEventListener("click", function(){
if (!tabCreated) {
// create a new tab
chrome.tabs.create({
url: this.href
}, function(tab) {
tabNumber = tab.id; // return ID of created tab
tabCreated = true;
});
} else {
// reload the created tab
chrome.tabs.reload(tabNumber, null);
}
}, false);
The biggest problem of your specification is that this kind of mechanism must be implemented for each browser separately and requires a plugin installation. If the link is the only browser-level access, you should consider changing its behavior so he can be part of the current page behavior.
Hope this helps! :-)
I want to create an extension for automatically logging into my servers. So I created a background page to check the current URL and if it conforms to my URL regex, I'll display the page action icon. On click of the page action I'm opening a popup with some fields. I need to get the currently opened URL and fill it in one of the fields in the popup(like when we click the standard bookmark page action, the URL gets automatically filled in the popup that opens). How can I do something like this in chrome extensions? I tried Message Passing from the background page to the popup html but it is not working. Is it possible to send messages like that? Also I tried setting onload for the popup html file but i noticed that it is not triggering. Please suggest a suitable method to deal with this scenario.
Use chrome.tabs.query with the following parameters:
queryInfo object:
active: true - To get the active tab
lastFocusedWindow: true - To select the active window
callback function:
This function receives one argument: An array of matched tabs. Since only one window can be active, and one tab within this window, the array has only one element. This element is an object with the Tab signature.
Code snippet:
// Do NOT forget that the method is ASYNCHRONOUS
chrome.tabs.query({
active: true, // Select active tabs
lastFocusedWindow: true // In the current window
}, function(array_of_Tabs) {
// Since there can only be one active tab in one active window,
// the array has only one element
var tab = array_of_Tabs[0];
// Example:
var url = tab.url;
// ... do something with url variable
});
The activeTab permission is sufficient for this to work.
You can also use promises for a cleaner way of retrieving a tab:
getCurrentTab().then(function(tab){
// Do something w/tab
});
function getCurrentTab(){
return new Promise(function(resolve, reject){
chrome.tabs.query({
active: true, // Select active tabs
lastFocusedWindow: true // In the current window
}, function(tabs) {
resolve(tabs[0]);
});
});
}