【问题标题】:Chrome extension working in backgroundChrome 扩展在后台工作
【发布时间】:2016-03-10 18:15:18
【问题描述】:

我正在开发一个 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. 如何在 popup.html 中显示来自 popup.js 的 javascript 内容

【问题讨论】:

    标签: javascript html google-chrome-extension


    【解决方案1】:

    问题 #1

    您可以使用content scripts 访问网页,获取信息并将其通过messaging passing 传递给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 都存在于扩展进程中,因此彼此之间有多种通信方式。您可以参考之前的帖子了解更多详情。 How to communicate between popup page and background page and store the info that I already get?

    第三部分

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

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

    附录

    要获得你想要显示的值,你也可以只对网站进行 ajax 调用,查询返回的 DOM 并检索你想要的数据。所有这些都可以通过 popup.js 完成。示例代码看起来像

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

    【讨论】:

    • 我不喜欢这个答案,因为它只提到(“你需要”)内容脚本作为从页面上刮下信息的可能性。通常(但并非总是)XHR 无需打开选项卡即可解决此问题。
    • @Xan,谢谢提及,我会更新答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    相关资源
    最近更新 更多