简体   繁体   中英

How to access chrome extension local storage data from content scripts?

I'm building a chrome extension to autologin to a website. My plane is like this.

  1. Get Username and Password(Done). popup
  2. Store in Local Storage(I'm using extension local storage)(Done).
  3. After that, when I go to the login page(website login page), extension will trigger and get the username and password in the Local storage(I Stuck this part).
  4. Finally, It will add those values in to input fields values and trigger the login button.

The problem is I don't know how to access the extension local storage in content scripts js file(login.js). When I get data form local storage data it's says 'null' because It's search the website local storage. I want to know how to read extension local storage data from content scripts js(login.js).

manifest.json

{
  "name": "Autologin",
  "description": "Using this extention you can login always to your website account without entering username and password!",
  "version": "1.0",
  "manifest_version": 2,
  "background": {
    "service_worker": "background.js"
  },
  "icons": {
    "16": "images/logo16.png",
    "32": "images/logo32.png",
    "64": "images/logo64.png",
    "128": "images/logo128.png"
  },
  "permissions": [
    "tabs",
    "storage",
    "notifications",
    "http://*/",
    "https://*/"
  ],
  "content_scripts": [
    {
      "matches": ["website URL here"],
      "js": ["login.js"]
    }
  ],
  "browser_action": {
    "default_icon": "images/logo128.png",
    "default_popup": "popup.html"
  }
}

popup.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Autologin</title>
  </head>
  <body>
    <div class="container">
      <img src="images/logo32.png" alt="logo" />
      <h3>USJP LMS Autologin</h3>
      <p>Please enter your user credentials</p>
      <label for="username">Username</label>
      <br />
      <input
        type="text"
        name="username"
        id="username"
        placeholder="Username"
        required
        maxlength="10"
        autocomplete="off"
      />
      <br />
      <label for="passowrd">Password</label>
      <br />
      <input
        type="password"
        name="password"
        id="password"
        placeholder="Password"
        required
        maxlength="20"
      />
      <br />
      <button type="button" id="setbtn">SET</button>
      <br />
      <small>Made with ❤ by</small>
    </div>

    <script src="popup.js"></script>
  </body>
</html>

popup.js

document.addEventListener("DOMContentLoaded", documentEvents, false);

function myAction(username, password) {
  //alert("The entered data is : " + username.value + " and " + password.value);
  if (username.value && password.value) {
    let user = [{ username: username.value, password: password.value }];
    localStorage.setItem("users", JSON.stringify(user));
    chrome.notifications.create("SaveData", {
      type: "basic",
      iconUrl: "images/logo64.png",
      title: "Successful!",
      message: "Your data successfully saved in Database",
      priority: 2,
    });
  } else {
    alert("Please, enter your user credentials");
  }
}

function documentEvents() {
  document.getElementById("setbtn").addEventListener("click", function () {
    myAction(
      document.getElementById("username"),
      document.getElementById("password")
    );
  });
}

//let userdata = localStorage.getItem("users");

Please help me, I want to know how to access local storage data in login.js file.

To get the extension local storage data first you have to do is change manifest.json background part like this.

old code

"background": {
    "service_worker": "background.js"
  }

Correct code

"background": {
    "scripts": ["background.js"]
  }

Then in background.js file you can place a Listener like this.

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.localstorage == "username") {
    sendResponse({
      username: JSON.parse(localStorage.getItem("users"))[0].username,
    });
  } else if (request.localstorage == "password")
    sendResponse({
      password: JSON.parse(localStorage.getItem("users"))[0].password,
    });
  else sendResponse({});
});

Finally, In content_script js file (according to the code 'login.js') you can send message to the listener to do your work.

let username = "";
let password = "";

chrome.runtime.sendMessage({ localstorage: "username" }, function (response) {
  username = response.username;
  document.getElementById("username").value = username;
});

chrome.runtime.sendMessage({ localstorage: "password" }, function (response) {
  password = response.password;
  document.getElementById("password").value = password;
  document.getElementById("loginbtn").click();
});

That's it. Simple. I hope you understand. If you have any problem with this please ask me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM