Any tips on transferring data from Background.js to autofill.js in my Google Chrome extension?

I've developed a Google Chrome extension that automatically fills in and submits usernames and passwords for specific websites like Gmail and Yahoo when the icon is clicked. Currently, the passwords and usernames are hardcoded in the autofill file. I'm now working on storing this information in a text (json) file called TheList, which the background page will read and turn into a string to access the necessary variables. My goal is to stop hardcoding the login details in Autofill and instead have them stored only in TheList. Can anyone suggest a way to achieve this? Thank you for taking the time to read this.

Below are the files involved:

Background.js

http://pastebin.com/XiCGXUAx

Autofill.js

http://pastebin.com/C0TiF9yB

TheList.json

{
"GmailUsername": "USERNAME1",
"GmailPassword": "PASSWORD1",
"YahooUsername": "USERNAME2",
"YahooPassword": "PASSWORD2"
}

Apologies for sharing links to my code due to formatting issues. I appreciate any assistance in accessing usernames/passwords from TheList and exploring encryption options for added security.

Answer №1

To accomplish this task, utilize the Messaging API.


Here is an idea to consider: establish a listener in your background.js and then insert your content script:

// background.js
chrome.runtime.onMessage.addListener(passwordRequest);

chrome.browserAction.onClicked.addListener(
    function (tab) {
        // ...
        chrome.tabs.executeScript(tab.id, {file: "autofill.js"});
    }
);

Subsequently, your content script will initialize and communicate the tab's domain back to the background page:

// autofill.js
chrome.runtime.sendMessage({domain: location.hostname}, fillPassword);

In the background page, handle this message accordingly:

// background.js
// Option 1: synchronous functions for retrieving username/password
function passwordRequest(request, sender, sendResponse) {
    var username = getUsername(request.domain);
    var password = getPassword(request.domain, username);
    if(password !== undefined) {
       sendResponse({username: username, password: password});
    } else {
       sendResponse({error: "No password found for " + request.domain});
    }
}

// Option 2: asynchronous storage API
function passwordRequest(request, sender, sendResponse) {
    getCredentials(                   
        function(username, password){ 
            if(password !== undefined) {
               sendResponse({username: username, password: password});
            } else {
               sendResponse({error: "No password found for " + request.domain});
            }          
        }
    );
    return true; 
}

In the content script, manage the response using a callback function:

// autofill.js
function fillPassword(response){
    if(response.error){
        console.warn(response.error);
        alert(response.error);
    } else {
        // autofill with response.username and response.password
        // ...
    }
}

Consider storing domain-specific IDs for form fields along with credentials for additional functionality.

Note: The above code has not been tested.


Regarding data storage, it would be wise to explore alternatives to fetching local files with XHR, especially for writing to them. View options for local data storage here.


Security must also be a top priority. Understand that there is no foolproof method to securely store sensitive information within a Chrome extension. Consult these discussions for more insight: Password storing in Google Chrome content scripts, How to store a password as securely in Chrome Extension?

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

I'm struggling to figure out how to specify the data type for storing an array of objects in a variable using React.useState

I am currently working on extracting values from an .xlsx file using the SheetJS library. Below, I will provide the code snippets, errors encountered, and the different approaches I have attempted. Data extracted from var dataToJson: (6) [{…}, {…}, { ...

Executing JavaScript code in the Selenium IDE

I'm having trouble figuring out how to execute JavaScript within the Selenium IDE. The objective is to enter text into an input field, with a backend setup that verifies the current time in the input field for testing purposes: Here's the input f ...

The process of retrieving request data from axios.get and storing it in the Redux store

Recently delving into Redux, I'm curious about how to retrieve request data from a GET method. Upon mounting the component, you can use axios to send a GET request to '/api/v3/products', passing in parameters like pageNumber and pageSize. ...

Refresh needed for Material UI styles to load correctly in Next JS

UPDATE: Reproducible issue https://github.com/ganavol409/next-material-ui-classes-bug Issue seems to be related to Higher Order Components and importing useStyles from Material UI Implemented Solution: https://github.com/mui-org/material-ui/blob/master/ ...

Looking to target an element using a cssSelector. What is the best way to achieve this?

Below are the CSS Selector codes I am using: driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg-technik='append_numbers']")).click(); driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg- ...

Angular directive used to create a nested tree list

Currently struggling with a nested list Directive in Angular. Whenever I attempt to run the code, the browser crashes due to the recursive call of the directive. My goal is to display a new list item if the data's children property contains items. H ...

JQuery enhances the functionality of tabs in web development

I have implemented the jQuery UI tabs control on my website. I am dynamically adding new tabs based on certain logic using the code snippet below: $("#div_Tabs").tabs("add", "/Game/PlayGame?matchID=" + result.MatchID, "Play with " + userName); The issue ...

I have run into a roadblock when trying to generate dynamic pages with Gatsby

Utilizing Gatsby in my current project, I am attempting to implement pagination on a specific page. Following the instructions provided at https://www.gatsbyjs.org/docs/adding-pagination/ and this additional resource , but encountering issues. In my gatsb ...

Modify the row's background color after clicking the delete button with jquery

Greetings, I am facing an issue with changing the color of a row in a table when clicking on a delete button. Despite trying various methods, I have not been successful. How can I modify the ConfirmBox() method to change the row's color? Your assistan ...

Font size for the PayPal login button

I am looking to adjust the font size of the PayPal Login button in order to make it smaller. However, it appears that the CSS generated by a script at the bottom of the head is overriding my changes. The button itself is created by another script which als ...

Output JSON data to an HTTP response in JavaServer Faces

Is there a way to generate dynamic charts using the JavaScript Library "D3.js" within JSF? By dynamically, I mean having a Java method retrieve data from a database and outputting it as JSON. The method for this task has already been written and proven suc ...

Strange ASP.NET Redirection/Submission Problem

My code is enclosed in a try/catch block with a redirect to another page, but I'm encountering a problem. When a user clicks on a submit button, instead of redirecting to the intended page, the page simply refreshes and stays on the same page. This is ...

Using jQuery to smoothly scroll horizontally to a specific div element

In my project, I aspire to create a layout similar to the BBC website: with a side scroll from section to section. Here is my code and the issue I am encountering: jsFiddle: http://jsfiddle.net/neal_fletcher/kzQFQ/2/ HTML: <div class="wrapper"> ...

html/css - techniques for transitioning a centered image on a landing page into a navbar logo when scrolling

Creating a minimalist navbar without the use of JavaScript or custom CSS is easier than you think. <nav class="navbar navbar-expand-md navbar-light bg-faded"> <a class="navbar-brand" href="#"> <img src=&qu ...

Display Buttons in a Horizontal Row and Highlight the Active Button

I am presenting four buttons that trigger POST requests, therefore they are enclosed in a form: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784 ...

Tips on how to retrieve an Observable Array instead of a subscription?

Is there a way to modify this forkJoin function so that it returns an observable array instead of a subscription? connect(): Observable<any[]> { this.userId = this.authService.userId; this.habits$ = this.habitService.fetchAllById(this.userId); this.s ...

Utilizing Codeigniter for transmitting JSON data to a script file

When querying the database in my model, I use the following function: function graphRate($userid, $courseid){ $query = $this->db->get('tblGraph'); return $query->result(); } The data retrieved by my model is then encoded in ...

Error in IndexedDBShim.js: Your JavaScript code attempted to assign a value to a read-only property, which is not permitted in strict mode

I have recently started experimenting with the IndexedDB jQuery API as IndexedDB is not compatible with Safari or iPad. However, I encountered an error when running HTML only without being able to utilize anything in the files. The specific files I am refe ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

What are the implications of a project containing nested node_modules directories?

We are currently in the process of dividing our project into "sub modules" within a single repository. Our goal is to maintain aspects such as webpack configurations and express server globally, with a structure similar to the following: package.json serv ...