如何将数据从 popup.js 传递到内容脚本?

时间:2021-01-11 18:05:35

标签: google-chrome-extension

场景是用户将从弹出窗口中输入API_KEYSECRET并提交,并使用它们来获取数据。用户可以多次执行此操作,但是当我单击按钮两次时出现错误:Uncaught SyntaxError: Identifier 'API_KEY' has already been declared。有什么办法可以解决吗?我认为问题是 content.js 再次执行。有什么办法可以解决吗?

manifest.json

{
  "manifest_version": 2,
  "name": "ext-chrome",
  "description": "Test",
  "version": "1.0.0",
  "browser_action": {
    "default_popup": "popup.html"
  },
  "permissions": [
    "storage",
    "tabs",
    "http://*/",
    "https://*/"
  ]
}

popup.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="popup.js"></script>
  </head>
  <body style="width: 200px">
    <p>Serial Code Finder</p>
    <input id="apiKey" type="text" placeholder="API Key" />
    <input id="secret" type="text" placeholder="Secret" />
    <button id="send">Click Me</button>
  </body>
</html>

popup.js

window.onload = () => {
  document.getElementById('send').onclick = sendData
}

const sendData = () => {
  let data = {
    apiKey: document.getElementById('apiKey').value,
    secret: document.getElementById('secret').value
  }

  chrome.storage.local.set({
    data
  }, () => {
    chrome.tabs.executeScript({
        file: "content.js"
    })
  })
}

content.js

let API_KEY = ''
let SECRET = ''

chrome.storage.local.get('data', (items) => {
  API_KEY = items.data.apiKey
  SECRET = items.data.secret
})

console.log('api key: ', API_KEY)
console.log('secret: ', SECRET)

0 个答案:

没有答案