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

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

Related

How can I create a dynamic product page using HTML, CSS, and Javascript

I currently only know javascript. But the thing is I looked up how to do it and some people talk about something called localStorage. I have tried this and for some reason when I jump to a new page those variables aren't kept. Maybe I am doing something wrong? I jump to a new page via
and all I want do do is select a certain image. take that image to a new page and add it to that page.
I tried using the localStorage variables and even turning it into JSON.stringify and doing JSON.parse when trying to call the localstorage to another script. It didn't seem to work for me. Is there another solution?
This is some of my code. There are two scripts.
document.querySelectorAll(".card").forEach(item => {
item.addEventListener("click", onProductClick);
})
var div;
var productImg;
var ratingElement;
var reviewCount;
var price;
function onProductClick(){
// This took a week to find out (this.id)
// console.log(this.id);
div = document.getElementById(this.id);
productImg = div.getElementsByTagName('img')[0];
ratingElement = div.getElementsByTagName('a')[2];
reviewCount = div.getElementsByTagName('a')[3]
price = div.getElementsByTagName('a')[4];
console.log(div.getElementsByTagName('a')[4]);
var productData = [div, productImg,ratingElement,reviewCount,price];
window.localStorage.setItem("price", JSON.stringify(price));
}
function TranslateProduct(){
console.log("Hello");
}
This is script 2
var productPageImage = document.getElementById("product-image");
var myData = localStorage['productdata-local'];
var value =JSON.parse(window.localStorage.getItem('price'));
console.log(value);
// function setProductPage(img){
// if(productImg != null){
// return;
// }
// console.log(window.price);
// }
To explain my thought process on this code in the first script I have multiple images that have event listeners for a click. I wanted to Click any given image and grab all the data about it and the product. Then I wanted to move that to another script (script 2) and add it to a dynamic second page. yet I print my variables and they work on the first script and somehow don't on the second. This is my code. in the meantime I will look into cookies Thank you!
Have you tried Cookies
You can always use cookies, but you may run into their limitations. These days, cookies are not the best choice, even though they have the ability to preserve data even longer than the current window session.
or you can make a GET request to the other page by attaching your serialized object to the URL as follows:
http://www.app.com/second.xyz?MyObject=SerializedData
That other page can then easily parse its URL and deserialize data using JavaScript.
you can check this answer for more details Pass javascript object from one page to other

Pure javascript from console: extract links from page, emulate click to another page and do the same

I'm curious if it is possible with pure (vanilla) javascript code, entered into the browser console, to extract all links this (first) page, then emulate a click to go to another page, extract links there and go to the third page.
Extract links means to write them into console.
The same question as 1 but link to go to another page makes just an ajax call to update the part of the page and does NOT actually go to another page.
P.S. All links belong to one domain.
Any ideas how can this be done based on pure javascript?
As example, if you go to Google and enter some word ("example"), you may then open the console and enter
var array = [];
var links = document.getElementsByTagName("cite");
for(var i=0; i<links.length; i++) {
array.push(links[i].innerHTML);
};
console.log(array);
to display the array of URLs (with some text, but that's OK).
It is possible to repeat it 3 times from page 1 to page 3 automatically with pure javascript?
P.S. I should actually extract tags in the code above, so tags I named "links". Sorry for confusion (that doesn't change the question).
Thank you again.
If you want to write all the links into the console, you can use a more specific command
FOR GOOGLES
// Firstly, you get all the titles
var allTitles = document.getElementById("ires").getElementsByTagName("h3");
for(var getTitle of allTitles ) { // For each title, we get the link.
console.log(getTitle.getElementsByTagName("a")[0].href)
}
Then, you only need to simulate a click on the nav.
var navLinks = document.getElementById("nav").getElementsByTagName("a");
navLinks [navLinks.length-1].click() // Click on the "Next" button.
FOR ALL SITES
If you want to get all the links, just do the same command, grab the div ID you want id you only want some part of the page, then use getElementsByTagName("a")
You can find out how to use XHR or other to make raw AJAX request
Simple example found on Google :
// jQuery
$.get('//example.com', function (data) {
// code
})
// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
// code
}
httpRequest.open('GET', url)
httpRequest.send()

Open all links on page in new tabs and track those tabs

I know I cannot directly access the DOM from the main function in a firefox addon with the SDK, and therefore I cannot obtain the href values from the a tags directly either. How can I make my addon open all of the links on a page as new tabs and add those to an array? I don't want new tabs manually opened by the user to be tracked, just the ones created by this addon.
Partially solved the issue a while back so I figure I'll point out what I know.
Since the main script can't access the DOM itself, it can instead attach a worker to the current tab. The worker can read all of the links and store them as a list, then send that list back to the add-on. The add-on can then open new tabs directed at all the links in that list.
In main, add a content script to the tab:
function attachScript() {
var worker = tabs.activeTab.attach({
contentScriptFile: self.data.url("content-script.js")
});
worker.port.on("links", function(links) {
for each(var l in links) {
tabs.open(l);
}
}); // Start listening for links sent by the tab's worker
worker.port.emit("get-links"); // Request links from worker
}
In the content script, upon receiving a get-links message, read all the links and send them back using port:
self.port.on("get-links", handleMessage); // Start listening for requests for links on page
function handleMessage(message) {
var anchors = document.getElementsByTagName("a"); // Get all a elements on page
alert(anchors.length); // Report quantity of a elements found
var hrefs = [];
for each (var a in anchors) {
hrefs.push(a.href); // Add all target urls of a elements to array
}
self.port.emit("links", hrefs); // Send array of urls to add-on script
}
As for tracking the tabs, I imagine keeping a list of the workers would be the appropriate way to accomplish this. I haven't tried that part yet as I had to put this project down for a while.

Retrieving which tabs are open in Chrome?

Is there a way to retrieve all the tabs open and sort them in to an array in Chrome? So if Gmail and YouTube were open, there would be two entries in the array entitled "gmail.com" and "youtube.com".
Yes, here is how you can do this:
Note: this requires permission "tabs" to be specified in your manifest file.
chrome.windows.getAll({populate:true}, getAllOpenWindows);
function getAllOpenWindows(winData) {
var tabs = [];
for (var i in winData) {
if (winData[i].focused === true) {
var winTabs = winData[i].tabs;
var totTabs = winTabs.length;
for (var j=0; j<totTabs;j++) {
tabs.push(winTabs[j].url);
}
}
}
console.log(tabs);
}
In this example I am just adding tab url as you asked in an array but each "tab" object contains a lot more information. Url will be the full URL you can apply some regular expression to extract the domain names from the URL.
Unless you are building a plugin, there isn't a way that I know of to retrieve all of the names of the open tabs, especially if the tabs contain content from separate domains. If you were able to do such a thing, it could be quite a security issue!
You can check the Chrome documentation here: http://developer.chrome.com/extensions/devguide.html

"Can't execute code from a freed script" in IE8 using Javascript w/Prototype

This is my first question on here so here goes....
I've got an issue in IE8 where I have a popup form (window.showDialog()) used to edit receipt information in an accounting system.
This was working fine up until I had to add more content by adding a dynamically built table of input fields. I'm getting the information back in an array, however that's where my error seems to be occurring. var pinputs = []; is what seems to be causing the issue.
js function in the popup form:
function saveForm() {
if($('user_id')){
var user_id = $F('user_id');
} else {
var user_id = 0;
}
var payments = $$('.payment');
var pinputs = [];
for(var i=0; i<payments.length; i++){
pinputs.push($F(payments[i]));
}
window.returnValue = {received_of: $F('received_of'), user_id: user_id,
note: $F('note'), work_date: $F('work_date'), payment: pinputs};
window.close();
}
js function in the parent js file:
function modifyReceiptInformation(id) {
return window.showModalDialog('mod.php?mod=receipts&mode=receipt_edit_popup&wrapper=no&receipt_id=' + id, 'Modify Receipt',"dialogWidth:600px;dialogHeight:500px");
}
I found a similar situation already on here but that was involving the calling of functions from the child form which I'm not doing here. Perhaps I didn't understand the solution? I'm not an expert with JS so any input will be helpful.
--Edit--
Forgot to also add in here that the var payments = $$('.payment'); is the array of input fields in my template file.
You're probably trying to access methods on the array returned by the popup after the popup is closed. That returned array was constructed on the popup, and is dependent on the popup still existing to be usable.
So you have a few options:
don't close the popup from within the popup script. Get your parent handler to do what it needs with the array (such as cloning it in an array of its own with [].concat(popupArray) for example), then have it close the popup.
convert your array to a string to cross the popup/parent boundary. JSON.stringify()/JSON.parse() would do the job nicely if you don't care about IE6/7. That way, you can still close the popup from within the popup script (apparently, string objects don't get that particular problem with IE.)
I had the same problem, so I wrote this handy function to work around the issue.
// The array problem is when modalDialogue return values are arrays. The array functions
// such as slice, etc... are deallocated when the modal dialogue closes. This is an IE bug.
// The easiest way to fix this is to clone yourself a new array out of the remnants of the old.
//
// #param[in] ary
// The array, which has been passed back from a modal dialogue (and is broken) to clone
// #returns
// A new, unbroken array.
function cloneArray(ary) {
var i;
var newAry = [];
for(i=0; i<ary.length; i++){
if(Object.prototype.toString.call(ary[i]) == '[object Array]') {
newAry.push(cloneArray(ary[i]));
} else{
newAry.push(ary[i]);
}
}
return newAry;
}
Then you can use it thusly:
var selectedAry = window.showModalDialog("Window.jsp", inputAry, "dialogWidth:900px; dialogHeight:700px; center:yes; resizable: yes;");
var newAry = cloneArray(selectedAry);

Categories

Resources