简单Chrome扩展程序中的内容脚本问题

时间:2016-03-31 00:29:36

标签: javascript html google-chrome google-chrome-extension

我对编程非常陌生并且提出了一个简单的问题。

我正在编写一个简单的Chrome扩展程序,记录所有用户滚动并添加以像素为单位滚动的距离。我希望为每个网站跟踪它,将其保存到chrome.storage.local,然后在我的browser_action js中我想检索该数字并显示它。

问题是内容脚本似乎没有运行。每当滚动事件发生且没有发生时,我都会添加一个console.log来记录。这是我的文件:

ScrollerJS(这是我的conent脚本)

var totalScroll;
var lastKnownScrollPos = 0;

document.addEventListener("DOMContentLoaded", function(event) {
    window.addEventListener("scroll", function() {
        console.log(lastKnownScrollPos);
        totalScroll += Math.abs(window.scrollY - lastKnownScrollPos);
        lastKnownScrollPos = window.scrollY;
        chrome.storage.local.set({scroll: totalScroll});
    });
});

Popup.JS

document.addEventListener("DOMContentLoaded", function(event) {
  chrome.storage.local.get("count", function(data) {
  console.log(data)
  document.getElementById("#miles-scrolled").textContent = data.count;
});
})

Popup.HTML

<!doctype html>
<html>
  <head>
    <title>Scroller</title>
    <style>
      body {
        font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
        font-size: 100%;
        height:300px;
        width: 300px;
      }
      #status {
        /* avoid an excessively wide status text */
        white-space: pre;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 300px;
      }
    </style>
    <script src="popup.js"></script>
  </head>
  <body>
    <div id="status">You've scrolled this many miles:</div>
    <div id="miles-scrolled"</div>
  </body>
</html>

的manifest.json

{
"manifest_version":2,

"name":"Scroll by the Mile",
"description":"Measures distance scrolled in miles",
"version":"1.0",

"content_scripts":[
    {
        "matches": ["<all_urls>"],
        "js": ["scroller.js"]
    }
    ],

"browser_action": {
    "default_icon":"icon.png",
    "default_title":"Scroll by the Mile",
    "default_popup":"popup.html"
},

"permissions":[
  "activeTab",
  "<all_urls>",
  "storage"
]
}

我很感激任何帮助,找出为什么这不起作用/如果我离开基地。

1 个答案:

答案 0 :(得分:0)

查看run_at,默认情况下此部分为document_idle,这意味着内容脚本是在window.onload个事件触发后注入的,这意味着您无法捕获{{1}事件实际上你没有绑定你的事件监听器。

要解决这个问题,我想提供两种方法

  1. DOMContentLoaded添加到"run_at": "document_start",这意味着在构建任何其他DOM之前注入脚本。

    的manifest.json

    manifest.json
  2. { "manifest_version": 2, "name": "Scroll by the Mile", "description": "Measures distance scrolled in miles", "version": "1.0", "content_scripts": [ { "matches": [ "<all_urls>" ], "js": [ "scroller.js" ], "run_at": "document_start" } ], "browser_action": { "default_icon":"icon.png", "default_title": "Scroll by the Mile", "default_popup": "popup.html" }, "permissions": [ "activeTab", "<all_urls>", "storage" ] } 事件侦听器中提取,因为默认情况下,在注入内容脚本时,会确保DOMContentLoaded事件被触发。

    scroller.js

    DOMContentLoaded