简体   繁体   English

如何从内容脚本访问 chrome 扩展本地存储数据?

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

I'm building a chrome extension to autologin to a website.我正在构建一个 chrome 扩展来自动登录到一个网站。 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).之后,当我 go 到登录页面(网站登录页面)时,扩展程序将触发并获取本地存储中的用户名和密码(我卡住了这部分)。
  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).问题是我不知道如何访问内容脚本 js 文件(login.js)中的扩展本地存储。 When I get data form local storage data it's says 'null' because It's search the website local storage.当我从本地存储数据中获取数据时,它显示为“null”,因为它正在搜索网站本地存储。 I want to know how to read extension local storage data from content scripts js(login.js).我想知道如何从内容脚本 js(login.js) 中读取扩展本地存储数据。

manifest.json 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 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 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.请帮助我,我想知道如何访问 login.js 文件中的本地存储数据。

To get the extension local storage data first you have to do is change manifest.json background part like this.要首先获取扩展本地存储数据,您必须像这样更改manifest.json背景部分。

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.然后在background.js文件中你可以像这样放置一个监听器。

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.最后,在content_script js 文件中(根据代码“login.js”),您可以向侦听器发送消息以完成您的工作。

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.如果您对此有任何问题,请询问我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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