我只想通过点击Chrome扩展程序中的按钮来显示我当前标签的网址。我尝试在popup.js中使用alert()但它无法正常工作。我是javascript和chrome扩展程序的新手,所以请怜悯:)
popup.html代码为:
<!doctype html>
<html>
<head>
<title>Save URL</title>
<script src="popup.js"></script>
</head>
<body>
<h2> FYDP: Save Current Tab URL </h2>
<button id="Get URL"> Get the URL of this page! </button>
</body>
</html>
popup.js代码是:
function getCurrentTabUrl(callback) {
var queryInfo = {
active: true,
currentWindow: true
};
chrome.tabs.query(queryInfo, function(tabs) {
var tab = tabs[0];
var url = tab.url;
document.getElementById("Get URL").onclick = alert(url);
console.assert(typeof url == 'string', 'tab.url should be a string');
callback(url);
});
}
manifest.json代码是:
{
"manifest_version": 2,
"name": "Save URL",
"description": "This extension saves the URL of the current tab in a
variable ",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Click here!"
},
"permissions": [
"activeTab"
]
}
答案 0 :(得分:0)
您实际上无法在Chrome扩展程序弹出窗口中显示来自javascript事件的警报(有关详细信息,请参阅this other stack overflow post)。但如果你好奇,如果可能的话, 会是什么样子,这就是它的原因(我在你的代码中改变了一些东西):
get-url
<body>
的末尾,因为您正在使用querySelector
,并且脚本标记是在线执行的,这意味着只有之前的元素脚本标记已呈现。也就是说,您必须在按钮标记tabs
权限 - 您需要它来查询所有标签popup.js:
function getCurrentTabUrl() {
var queryInfo = {
active: true,
currentWindow: true,
}
chrome.tabs.query(queryInfo, function(tabs) {
var tab = tabs[0]
alert(tab.url)
})
}
document.querySelector('#get-url').addEventListener('click', getCurrentTabUrl)
popup.html:
<html>
<head>
<title>Save URL</title>
</head>
<body>
<h2> FYDP: Save Current Tab URL </h2>
<button id="get-url"> Get the URL of this page!</button>
<script src="popup.js"></script>
</body>
</html>
的manifest.json:
{
"manifest_version": 2,
"name": "Save URL",
"description": "This extension saves the URL of the current tab in a variable",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Click here!"
},
"permissions": [
"activeTab",
"tabs"
]
}