将变量从popup.js传递到background.js,接收到未定义

Passing variable from popup.js to background.js received as undefined

本文关键字:js background 未定义 变量 popup      更新时间:2023-09-26

我试图使一个chrome扩展,当用户输入一个网址,并按下按钮"去"它加载在一个新的选项卡网页。我试图通过使用消息传递将用户输入传递到后台页面,但由于某种原因,当后台试图访问消息时,输入总是未定义的。我想知道如何适当地让用户输入到后台,这样它就会在一个新的选项卡中打开链接。

Manifest.json

{
  "manifest_version": 2,
  "name": "My Cool Extension",
  "version": "0.3.1.2",
  "description":"User can enter in wepage and press button to open webpage in new tab.",
  "background": {
    "scripts": ["background.js"]
  },
  "content_scripts": [
    {
      "matches": [
    "<all_urls>"
  ],
  "js": ["jquery-2.1.4.min.js", "content.js"]
}
  ],
  "browser_action": {
    "default_icon": "arrow.png",
    "default_popup":"popup.html"
  },
  "permissions": [
          "tabs",
          "http://*/*",
          "https://*/*"
        ],
  "icons":{
         "128":"arrow.png"
  }
}

background.js

chrome.runtime.onMessage.addListener(
function(request,sender,sendResponse)
{
    if(request.message == "Go_To_Clicked"){
       chrome.tabs.create({ url: chrome.tabs.create({ url: request.websiteVar})
}
     })

popup.html

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
<style>
  body {
    font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
    font-size: 100%;
  }
  #status {
    /* avoid an excessively wide status text */
    white-space: pre;
    text-overflow: ellipsis;
    overflow: hidden;
    max-width: 400px;
  }
</style>
<script src="popup.js"></script>
  </head>
  <body>
<div id="status"></div>
<img id="image-result" hidden>
<form>
  Enter Link:
  <br>
    <input id = "userWebsite" type="text" name="webLink">
  </br>
</form>
<button id = "goTo" type="button">Go to</button>
<button id = "save" type="button">Save</button>
<script type="text/javascript" src="popup.js"></script>
  </body>
</html>

popup.js

window.onload=function()
  {
   document.getElementById("goTo").onclick=function()
    {
  var websiteVar = document.getElementById('userWebsite').value;
  chrome.runtime.sendMessage({ website: websiteVar, message:"Go_To_Clicked"});
}
  }

您需要使用request.website而不是request.websiteVar(侦听器端不存在)

    chrome.tabs.create({ url: request.website},function(tab){
       // Callback     
    })