我正在尝试制作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"});
}
}
答案 0 :(得分:1)
您需要使用request.website
代替request.websiteVar
(在听众端不存在)
chrome.tabs.create({ url: request.website},function(tab){
// Callback
})