[英]Unable to open a new tab using a button within a Chrome Extension popup
我正在嘗試編寫一個Chrome Extension彈出窗口,該彈出窗口中將包含一些選項:基於所選的菜單,我必須生成一個URL並將其加載到新標簽中。 我已經嘗試了幾乎所有找到的解決方案,但是仍然無法理解自己在做什么錯。 我在下面提供了詳細信息。
的manifest.json
{
"name": "New Extension",
"version": "1",
"description": "New Extension",
"manifest_version": 2,
"browser_action": {
"name": "New Extension",
"default_popup": "popup.html",
"default_icon": "icon.png"
},
"permissions": [ "tabs" , "<all_urls>"]
}
popup.html
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
<script src="popup.js"></script>
</head>
<body style="width: 400px" bgcolor= "#FFFFFF">
Operation:<input type="radio" name="operation" id="Google" checked="checked">Google
<input type="radio" name="operation" id="Yahoo">Yahoo<br/>
<input type="button" name="btngenerate" id="btngenerate" value="Generate" />
</body>
</html>
popup.js
document.getElementById("btngenerate").addEventListener('click', function() {
alert("in generate URL");
var URL = "http://google.com";
if (document.getElementById("yahoo").checked == true)
URL = "http://yahoo.com";
chrome.tabs.create({url: URL});
});
當我嘗試執行此操作時,我可以看到彈出窗口,但是,當我單擊“生成”時,什么也沒有發生。 我的代碼有什么問題?
Chrome開始按標記解析HTML文件標記並填充DOM。
一旦遇到<script>
標記,它將立即執行。
因此,您的代碼將在DOM中存在#btngenerate
之前執行。
您需要將其包裝在一個事件中,該事件在完全讀取文件並構造DOM之后將觸發:
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("btngenerate").addEventListener(/*...*/);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.