Chrome扩展程序在后台工作

Chrome extension working in background

本文关键字:后台 工作 程序 扩展 Chrome      更新时间:2023-09-26

我正在开发一个Chrome扩展程序,其目标是在后台访问网站,并从中显示一个特定值,用户应该通过单击Chrome扩展程序图标看到该值,而无需打开特定选项卡。

这是我的popup.html

<!doctype html>
<html>
  <head>
    <title>Notification Analyzer</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <h1>Current Notifications</h1>
    <a id="myLink" href ="https://website.com/notify/index.php"></a>
  </body>
</html>

而我的popup.js

a = document.getElementsByClassName('notificationArea').item('span').childNodes[6].textContent; // this is the value which I want to display on click of the extension icon
window.onload = function() {
   document.getElementById("myLink").innerHTML=a; 
} // Here, trying to add the value to the popup.html element 

如果我尝试在特定网站选项卡上弹出为警报框,它会起作用。但当网站选项卡未打开时,不在后台。

所以这里有两个问题:

  1. 如何使扩展程序能够在后台访问网站内容?

  2. 如何从弹出窗口.js弹出窗口中显示javascript内容.html

问题 #1

您可以使用内容脚本访问网页,获取信息并通过消息传递将其传递给background page

问题 #2

第一部分

事实上,问题#1也是如此。以下代码应属于content script

a = document.getElementsByClassName('notificationArea').item('span').childNodes[6].textContent; // this is the value which I want to display on click of the extension icon

第二部分

然后,您可以使用上面引用的"消息传递"将其从content script传递到background page

由于popup.jsbackground page都生活在扩展过程中,因此彼此之间有很多通信方式。您可以参考上一篇文章了解更多详情。如何在弹出页面和背景页面之间进行通信并存储我已经获得的信息?

第三部分

最后,您可以使用popup.js中的代码来设置链接的文本。

window.onload = function() {
    document.getElementById("myLink").innerHTML=a; 
} // Here, trying to add the value to the popup.html element

附录

要获取要显示的值,您还可以对网站进行 ajax 调用,查询返回的 DOM 并检索所需的数据。所有这些都可以通过弹出窗口.js来完成。示例代码如下所示

$.ajax({
    url: url,
    callback: function (data) {
        var mydata = $(data).find('You css selector');
        document.getElementById("myLink").innerHTML=mydata; 
    }
});