简体   繁体   English

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

[英]Passing variable from popup.js to background.js received as undefined

I'm trying to make a chrome extension that when the user enters in a web address and presses the button "Go to" it loads the webpage in a new tab. 我正在尝试创建一个Chrome扩展程序,当用户输入网址并按下“转到”按钮时,它将在新标签页中加载网页。 I am trying to pass the user input to the background page by using message passing but for some reason when the background tries to access the message the input is always undefined. 我试图通过使用消息传递将用户输入传递给后台页面,但是由于某些原因,当后台尝试访问消息时,输入始终是未定义的。 I was wondering how to appropriately get the user input to the background so it will open the link in a new tab. 我想知道如何适当地使用户输入到后台,以便它将在新选项卡中打开链接。

Manifest.json 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 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 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 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"});
}
  }

You need to use request.website instead of request.websiteVar (which does not exist at listener end) 您需要使用request.website而不是request.websiteVar (在侦听器端不存在)

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

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

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