Is there a way to store the URLs that a user visits locally with a Chrome extension using JavaScript?

I am working on a Chrome extension that will save the URL link of the active tab when a user clicks on the extension icon. The goal is to store this URL in local storage and keep it saved until the active window is closed. I have set up an array called tablink to hold these URLs.

Below is the content of my manifest.json:

{
    "manifest_version": 2,

    "name": "saveLink",
    "version": "1.0",

    "browser_action": {
        "default_icon": "xyz.png",
        "default_popup": "popup.html",
        "default_title": "saveLink"
    },
    "permissions": [
        "activeTab",
        "storage",
        "tabs"
    ]
}

Additionally, here is the content of my popup.js, which contains JavaScript code for the associated popup.html:

var tablink = [];
function getTabUrl(){
  chrome.tabs.getSelected(null,function(tab) {
    var len = tablink.length;
    if(len == 0){
      tablink[0] = tab.url;
    }
    else {
      tablink[len] = tab.url;
    }
    console.log(tablink);
  }
}

document.addEventListener("DOMContentLoaded", function() {
  getTabUrl();
  link.addEventListener('click', function() {
    chrome.tabs.update({url: 'https://www.google.com/'});
  });
});

Currently, I am facing issues as the console is not printing anything. Additionally, the extension's button, which should redirect to google.com, no longer works after adding the code to save tab links. Any guidance on potential solutions would be greatly appreciated.

Answer №1

How to store the URL of the current tab in a list when opening a popup

popup.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  var tabUrl = tabs[0].url;
  chrome.storage.local.get('urlList', function(item){
    var newUrlList = item.urlList;
    newUrlList.push(tabUrl);
    console.log(newUrlList);
    chrome.storage.local.set({urlList: newUrlList});
  });
});

Insight: The code uses the tabs.query method to retrieve information about the currently active tab in the window. It then retrieves the existing list of URLs saved in local storage and appends the current tab's URL to it using the push() method before updating the stored list.


UPDATE: The code snippet above assumes that urlList is already defined within chrome.storage. The following modification ensures that urlList is initialized as an empty array if it doesn't exist.

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  var tabUrl = tabs[0].url;
  chrome.storage.local.get({'urlList':[]}, function(item){
    var newUrlList = item.urlList;
    if (newUrlList.indexOf(tabUrl) === -1) {
      newUrlList.push(tabUrl);
    }
    console.log(newUrlList);
    chrome.storage.local.set({urlList: newUrlList});
  });
});

Insight: By providing a default value of an empty array in get({'urlList':[]}), the code initializes urlList if it doesn't have a value yet. Additionally, an additional check ensures that duplicate URLs are not added to the list.

In cases where you want to verify the functionality of chrome.storage, consider clearing the storage with chrome.storage.local.clear();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to individually update fields using Prisma?

I am facing a challenge with updating fields individually for an object named Post. This object has three fields: title, content, and summary. Situation To save a post in the database, I can fill in just the title field initially and leave the other fiel ...

Error thrown due to syntax issues in react.d.ts declaration file in TypeScript

Currently, I am attempting to integrate react with typescript in my project. However, typescript is generating syntax errors for the react.d.ts file sourced from Github: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react The encountered ...

Adjust the position of the footer up or down based on changes in page content height

If I have jQuery at my disposal, how can I achieve the following task? There is a div on the page with dynamic content and no fixed height. The height of this div changes as users type and content appears or disappears accordingly. Although everything is ...

The function of JQuery .click() is successful when used on a local machine, however it is not functioning

I am facing a puzzling issue. The code in question functions perfectly on my local server, but once I uploaded it to my hostgator server, a specific function no longer executes. When I set a breakpoint in the Firefox debugger, I noticed that the function i ...

"Every time ajax is called, it will always generate

function lks() { var groupname = document.getElementById('groupname').value; $.ajax ({ url: 'verifyGroup.php?groupname='+groupname, type: 'get', ...

Counting the elements on a page using Selenium and Node.js: A step-by-step guide

I've been experimenting with Selenium in Javascript using NodeJS and I'm trying to tally up some elements based on CSS selectors. So far, I've attempted a few methods: client.findElements(By.css(".some-class")).size(); However, I encounte ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Update the ng-model using an Angular service

I am currently working on an Angular application that includes a textarea: <textarea id="log_text_area" readonly>{{logger}}</textarea> In addition, there is a Logger service designed to update this textarea. angular.module('app').f ...

Have you ever wondered how to disable a tooltip in React Material UI after clicking on it? Let

I am working with a Material-UI tab component and I would like to include a tooltip feature. The issue I am facing is that the tooltip does not disappear when I click on the tab. It should hide after clicking on the tab. Currently, the tooltip remains vi ...

Experiencing problems with various React Carousel libraries when it comes to displaying

I have been attempting to integrate Carousel libraries into my react app, but I am encountering a common issue with all of them. The Carousels show the items on the first slide, but subsequent slides do not display any items, even though they exist within ...

Oops! An error occurred while trying to find the _mongodb._tcp.blog-cluster-0hb5z.mongodb.net. Please check your query settings and try again

My free Mongo Atlas cluster suddenly stopped connecting, even though everything was working fine before. Strangely, I can see that data has been collected on the MongoDB website. It's puzzling why this issue occurred and now my entire site won't ...

Unexpected results occurring during JavaScript refactoring process

Having this repetitive code snippet that switches between two radio buttons being checked within my $(document).ready(): $(document).ready(function () { $("#New").click(function () { var toggleOn = $("#New"); var tog ...

Utilize generics to define the data type of the output

Within my Angular service, there is a method that retrieves data from Sync Storage: getFromSyncStorage(key: string): Promise<Object | LastErrorType> { return new Promise(function (resolve, reject) { chrome.storage.sync.get(key, function ( ...

Static express is failing to load the node_modules folder

Why am I facing difficulties with my website not being able to use the node_modules directory on my server? const express = require('express'); const app = express(); app.use(express.static(__dirname + '/public')); app.listen(8080, &ap ...

Avoid form submission when the 'enter' key is pressed in Edge, but not in Chrome or Firefox

I'm dealing with an issue in HTML where a 'details' tag is set to open and close when the user presses enter. However, on Edge browser, pressing enter on the 'details' tag actually submits the form. I've been tasked with preve ...

Waiting for state changes in React by using the UseState Hook

I am currently working on a function that manages video playback when clicked, and I need to set consecutive states using the useState hook. However, I want to ensure that the first state is completed before moving on to the next setState without relying ...

Tips and techniques for implementing push notifications in front-end applications without the need for a page refresh

I am working on a Python program that inserts data into a XAMPP database. I am looking for a way to continuously monitor the database for any changes and automatically send updates to the frontend without relying on click events. Is there a method simila ...

What is the best way to fulfill a promise after a CSV file has finished being read?

I have been utilizing the 'fast-csv' module that can be found at this link (https://www.npmjs.org/package/fast-csv), but I am open to switching to a different one. I attempted promised-csv (https://www.npmjs.org/package/promised-csv) but I had tr ...

What enables typescript to be eligible for transpiling is its equivalent level of abstraction to javascript?

Transpilation is the act of converting code from one language to another with a similar level of abstraction. Can you point out some distinctive characteristics that indicate TypeScript transpires into JavaScript? ...

How come JSON.parse is altering the data within nested arrays?

In my journey to master Angular 2, I decided to challenge myself by creating a Connect Four game using Angular CLI back when it was still utilizing SystemJS. Now, with the switch to the new Webpack-based CLI, I am encountering a peculiar issue... The fun ...