我编写了一个chrome扩展程序,可以成功记录滚动数据的所有用户(带有像素数量的时间戳)。此数据当前正在控制台中登录。
然而我的下一步却给我带来了一些麻烦。
然后我希望将创建的每个数据日志都发送到外部网页。即,页面将自动更新并存档每个新的带时间戳的条目/像素计数器扩展记录。
通过在DOM事件中传递一条简单的消息,我已经能够在扩展和网页之间进行通信。但是我无法获得扩展以发送它正在收集的滚动数据。
我觉得我很亲近,而且我已经阅读了Google的Messaging API,但我觉得有点迷失。
到目前为止,这是我的代码:
的manifest.json
{
"manifest_version": 2,
"name": "Caressing the Silver Rectangle",
"description": "Measures Jesse Bowling's distance scrolled in pixels on Google Chrome",
"version": "1.1",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"scroller.js"
],
"run_at": "document_start"
}
],
"background": {
"scripts": ["background.js"]
},
"externally_connectable": {
"matches": ["http://*/*jessebowling.space/caressingthesilverrectangle/*"]
},
"browser_action": {
"default_icon":"icon.png",
"default_title": "Caressing the Silver Rectangle",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"<all_urls>",
"background",
"tabs",
"storage"
]
}
Background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("background.js got a message")
console.log(request);
console.log(sender);
sendResponse("bar");
}
);
Scroller.js
/*jslint devel: true */
// The ID of the extension we want to talk to.
var caressingthesilverrectangleId =
"http://*/*jessebowling.space/caressingthesilverrectangle/*"
var totalScroll;
var lastKnownScrollPos = 0;
window.addEventListener("scroll", function () {
"use strict";
console.log(lastKnownScrollPos);
totalScroll += Math.abs(window.scrollY - lastKnownScrollPos);
lastKnownScrollPos = window.scrollY;
chrome.storage.sync({ scroll: totalScroll });
function (response) {
console.log(response);
}
});
// send data through a DOM event
document.dispatchEvent(new CustomEvent('csEvent', {detail:
totalScroll}));
// Make a simple request:
chrome.runtime.sendMessage(caressingthesilverrectangleId,
{getTargetData: true},
function(response) {
if (targetInRange(response.targetData))
chrome.runtime.sendMessage(caressingthesilverrectangleId,
{activateLasers: true});
});
// Start a long-running conversation:
var port = chrome.runtime.connect(caressingthesilverrectangleId);
port.postMessage(chrome.storage.sync({ scroll: totalScroll }));
答案 0 :(得分:0)
我猜你所在的部分
var port = chrome.runtime.connect(caressingthesilverrectangleId);
port.postMessage(chrome.storage.sync({
scroll: totalScroll
}));
是您尝试发送邮件的地方。但是,您发送的消息是chrome.storage.sync的结果,它始终为undefined
。您可能希望拆分这两个调用,以便实际发送一些数据,如:
var port = chrome.runtime.connect(caressingthesilverrectangleId);
chrome.storage.sync({
scroll: totalScroll
});
port.postMessage({
scroll: totalScroll
});