【发布时间】:2019-02-03 01:19:01
【问题描述】:
我有一个 JavaScript 文件,我在其中使用 Chrome 扩展程序来收集有关网页的数据,我想在 popup 中显示它。我是 Web 开发的新手,并且无法确定在执行某些事件侦听器时将此页面信息作为文本从我的 .js 文件发送到我的 .html 文件的最佳方式。我试图写的元素是output1。
popup.js
chrome.tabs.onActivated.addListener(function (tab) {
chrome.tabs.query({
active: true,
currentWindow: true
},
function (tabs) {
var tab = tabs[0];
var id = tab.id;
var url = tab.url;
var title = tab.title;
var host = new URL(url).hostname;
console.log("id: " + id + "\nurl:" + url + "\nhost:" + host + "\ntitle: " + title);
output1.text = host;
});
});
popup.html
<!doctype html>
<html>
<head>
</head>
<body>
<h3>Domain output</h3>
<output name="output1"></output>
<script src="popup.js"></script>
</body>
</html>
【问题讨论】:
-
大多数元素中没有
text这样的属性。您可能是指textContent。还假设弹出窗口是 browserAction 弹出窗口,onActivated 侦听器将不起作用,因为弹出窗口仅在显示时运行并在选项卡开关上隐藏时销毁 - 您完全不需要此侦听器,或者您需要重新设计扩展以使用背景脚本和不同的指示方法。请务必阅读文档中的架构文章。 -
明白了,你是对的。我很难找到正确的事件监听器,因为如果
browser_action有一个弹出窗口,chrome.browserAction.onClicked.addListener(function callback)不会触发,我这样做了。对于我正在测试的这个示例,我的目标是在单击扩展时在弹出窗口中简单地显示域。到目前为止,这仅在导航到已加载页面的页面时才有效,但我的目标是即使单击新选项卡并导航到网址也使其工作。
标签: javascript html google-chrome-extension google-chrome-app