Tabs.url is undefined - javascript

I have no clue what I'm doing wrong here! This should be working I believe. I'm writing a chrome extension and this should get the current tab's url and set the html of #current-tab to the url (for testing purposes). The code successfully gets to the callback, but it says that tab.url is undefined when I put it in an alert box, and it does not put it's value in #current-tab. Here's the code I have:
$('#get-tab').click(function(){
chrome.tabs.query({"active" : true}, function(tab){
for (var i = 0; i < tab.length; i++) {
alert(tab[i].url);
$('#current-tab').append(tab[i].url);
};
});
});

chrome.tabs.query actually returns an array of Tab objects, so you would have to reference the tab inside of the array (even if it is only one Tab):
$('#get-tab').click(function(){
chrome.tabs.query({"active" : true}, function(tab){
for (var i = 0; i < tab.length; i++) {
alert(tab[i].url);
$('#current-tab').append(tab[i].url);
};
});
});

I figured out what was wrong! Apparently you need to reload the extension to refresh changes to the manifest file! I had added the permissions later, but had not reloaded the extensions in the extension manager, so the change had not taken effect! We're rolling now!

Related

How can I make it work stably and insert as chrome extension?

This code performs saving and sorting innerHTMLtext of body by count of times you pressed combination of keys. It works, but at some point of time script stops working at all and it need to be changed or file that contain it has to be renamed to continue working. Besides I tryed add it as Chrome extension and in debug mode I see that script connected (it output conlose.log after DOMContentLoaded event handler), but it skips some blocks of code and after every fix different one. You can see this phenomenon in both "local server" and "browser extension" program modes. I tried somehow work out this problem, looked through a lot of forums and solutions and still dont have a solution. So it's sad that I cant end up my first mini project on native js(. Sincerely wish for your guidence.
popup.js
document.addEventListener("DOMContentLoaded", function() {
let inputEl = document.body;
inputEl.addEventListener("keydown", copy_paste);
});
console.log('It connected');
let storage = {};
function copy_paste(e) {
if (e.ctrlKey && e.key == "q") {
let inputValue = window.getSelection();
navigator.clipboard.writeText(inputValue).then(
navigator.clipboard.readText().then((text) => {
if (!storage.hasOwnProperty(text)) storage[text] = 1;
else storage[text] += 1;
mySort(storage);
})
);
}
}
function show(arrStorage) {
let parent = document.getElementById("insert");
parent.innerHTML = "";
for (let i = 0; i < arrStorage.length; i++) {
let para = document.createElement("h4");
para.innerText = arrStorage[i][0] + " : " + arrStorage[i][1];
parent.appendChild(para);
}
}
function mySort(storage) {
let arrStorage = [];
for (let key in storage) {
arrStorage.push([key, storage[key]]);
}
arrStorage.sort(function (a, b) {
return b[1] - a[1];
});
show(arrStorage);
}
navigator.clipboard.readText() requires clipboard-read permission of Permission API.
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard
The default value of clipboard-read is "prompt" (in my case) that means calling .readText() cause popup message to request permission of clipboard reading.
When your popup.html is opened in active tab (by defining popup.html as options page in manifest.json, for example), the popup message appears at keydown of cntl-q.
After clicking OK in the popup, the permission information is stored in Chrome.
You can see it in:
chrome://settings/content or
chrome://settings/content/all.
Unfortunately, when popup.html is opened as popup of browser action, the permission popup seems to be blocked, and your extension seems to stop.
I dont know why, but gess it is by security reason.
I think there is no way to permit clipboard-read in program without user interevension.

sucessive redirections using javascript

I'm trying to load sucessive urls using javascript from firefox developer console.
So far, I've tried with different versions of this code:
function redirect() {
var urls = ["http://www.marca.com", "http://www.yahoo.es"]
for (i = 0; i < urls.length; i++) {
setTimeout(location.assign(urls[i], 5000));
}
}
But the result of this code is that it only redirects to the last url from the array. Every page should be fully loaded before iterating to the next page.
I've also tried using window.onload, but with no luck either. It's always the last url which is loaded.
I guess this must be something very basic (I'm new to javascript), but can't find any solution to this.
Any help or hints of what I'm doing wrong here would be very appreciated. Thanks in advance!
Inspecting the console after running your code, it appears that a request is sent to the first URL but is soon aborted when the loop runs for the second time and instead it redirects to the latest URL.
My suggestion would be to open the pages in different tabs, if that works for you.
You can do,
for (i = 0; i < urls.length; i++) {
window.open(urls[i],"_blank");
}
This will open the pages in the new tabs.

Finding Window and Navigating to URL with Crossrider

I'm rather new to Javascript and Crossrider. I believe what I'm trying to do is a rather simple thing - maybe I missed something here?
I am writing an extension that automatically logs you into Dropbox and at a later time will log you out. I can log the user into Dropbox automatically, but now my client wants me to automatically log those people out of dropbox by FINDING the open Dropbox windows and logging each one of them out.
He says he's seen it and it's possible.
Basically what I want is some code that allows me to get the active tabs, and set the location.href of those tabs. Or even close them. So far this is what I got:
//background.js:
appAPI.ready(function($) {
// Initiate background timer
backgroundTimer();
// Function to run backround task every minute
function backgroundTimer() {
if (appAPI.db.get('logout') == true)
{
// retrieves the array of tabs
appAPI.tabs.getAllTabs(function(allTabInfo)
{
// loop through tabs
for (var i=0; i<allTabInfo.length; i++)
{
//is this dropbox?
if (allTabInfo[i].tabUrl.indexOf('www.dropbox.com')!=-1)
{
appAPI.tabs.setActive(allTabInfo[i].tabId);
//gives me something like chrome-extension://...
window.alert(window.location.href);
//code below doesn't work
//window.location.href = 'https://www.dropbox.com/logout';
}
}
appAPI.db.set('logout',false);
});
window.alert('logged out.');
}
setTimeout(function() {
backgroundTimer();
}, 10 * 1000);
}
});
When I do appAPI.tabs.setActive(allTabInfo[i].tabId); and then window.alert(window.location.href); I get as address "chrome-extension://xxx" - which I believe is the address of my extension, which is totally not what I need, but rather the URL of the active window! More than that, I need to navigate the current window to the log out page... or at least refresh it. Can anybody help, please?
-Rowan R. J.
P.S.
Earlier I tried saving the window reference of the dropbox URL I opened, but I couldn't save the window reference into the appAPI.db, so I changed technique. Help!
In general, your use of the Crossrider APIs looks good.
The issue here is that you are trying to use window.location.href to get the address of the active tab. However, in the background scope, the window object relates to the background page/tab and and not the active tab; hence you receive the URL of the background page. [Note: Scopes can't directly interactive with each others objects]
Since your objective is to change/close the URL of the active dropbox tab, you can achieve this using messaging between scopes. So, in your example you can send a message from the background scope to the extension page scope with the request to logout. For example (and I've taken the liberty to simplify the code):
background.js:
appAPI.ready(function($) {
appAPI.setInterval(function() {
if (appAPI.db.get('logout')) {
appAPI.tabs.getAllTabs(function(allTabInfo) {
for (var i=0; i<allTabInfo.length; i++) {
if (allTabInfo[i].tabUrl.indexOf('www.dropbox.com')!=-1) {
// Send a message to all tabs using tabId as an identifier
appAPI.message.toAllTabs({
action: 'logout',
tabId: allTabInfo[i].tabId
});
}
}
appAPI.db.set('logout',false);
});
}
}, 10 * 1000);
});
extension.js:
appAPI.ready(function($) {
// Listen for messsages
appAPI.message.addListener(function(msg) {
// Logout if the tab ids match
if (msg.action === 'logout' && msg.tabId === appAPI.getTabId()) {
// change URL or close code
}
});
});
Disclaimer: I am a Crossrider employee

closing the current tab in a chrome extention

I am writing a chrome extension that when clicked, will close the current tab after a given amount of time.
I am sending a message with the time, from popup.js to background.js. But the tab won't close.
The alert works when I uncomment it, so it seems to be just the remove line. I assume it's something about tab.id.
chrome.extension.onMessage.addListener(
function message(request, sender, callback) {
var ctr = 0;
ctr = parseInt(request.text, 10);
setTimeout(function() {
chrome.tabs.getCurrent(function(tab) {
//window.alert("Working?");
chrome.tabs.remove(tab.id, function(){});
});
}, ctr);
}
);
1.
chrome.extension has no onMessage event. I assume you mean the correct chrome.runtime.onMessage
2.
You have probably misunderstood(*) the purpose of chrome.tabs.getCurrent:
Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).
Since, you are calling it from a non-tab context (namely the background page), tab will be undefined.
(*): "misunderstood" as in "not bother to read the manual"...
3.
It is not clear if you want to close the active tab at the moment the timer is set or at the moment it is triggered. (In your code, you are attempting to do the latter, although the former would make more sense to me.)
The correct way to do it:
chrome.runtime.onMessage.addListener(function message(msg) {
var ctr = 0;
ctr = parseInt(msg.text, 10);
setTimeout(function() {
chrome.tabs.query({ active: true }, function(tabs) {
chrome.tabs.remove(tabs[0].id);
});
}, ctr);
});
Also, note that using functions like setTimeout and setInteval will only work reliably in persistent background pages (but not in event pages). If possible, you are advised to migrate to event pages (which are more "resource-friendly"), in which case you will also have to switch to the alarms API.

How can i get all URL's of a google chrome window

im currently developing an extension, but im kind of lost by the moment.
Basically, what i want it to do, its kind of what "OneTab" extension does.
So my first question is, after adding the listener to the extension button, and executing the function, i want to get all the url's of the current window, and store them in an array and the show them in the html file.
So im using this:
chrome.tabs.getSelected(null,function(tab) {
var tablink = tab.url;
console.log(tablink);
});
but its not working and im not sure how it will check all the tabs one by one.
Thanks in advance.
chrome.tabs.getSelected() will only get you the current tab.
In order to get the list of all the tabs in the current window, you need to use the chrome.windows API. This API will return an object of the current window which will have the list of tab objects.
Here is the sample code:
chrome.windows.getCurrent({"populate":true}, function(currentWindow) {
var tabURLs = [];
var tabs = currentWindow.tabs;
for (var i=0; i<tabs.length; i++) {
tabURLs.push(tabs[i].url);
}
console.log(tabURLs);
});
For details check:
http://developer.chrome.com/extensions/windows.html#method-getCurrent

Categories

Resources