【发布时间】:2015-12-19 09:00:57
【问题描述】:
我正在尝试编写一个 Chrome 扩展程序,在内容脚本和后台页面之间进行一些基本的通信。
在 Javascript 中,我会在内容页面和后台页面中注册监听器,例如在后台页面中:
chrome.browserAction.onClicked.addListener(function(tab) {
// Send a message to the active tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
});
(取自this tutorial)。
另一个适用于 Javascript 的示例:
// content.js
chrome.runtime.sendMessage({screenShot: true}, function(response) {
console.log("response: " + response);
});
// background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
alert('message received!');
console.log("request: " + request);
if (request.screenShot) {
// do something
}
});
如何将上述代码翻译成 ClojureScript?
我的第一次尝试是基于lein-chrome-extension模板创建一个项目,并使用Khroma的runtime/connect方法依赖于core-async。但是我在content.cljs 和background.cljs 脚本之间没有得到适当的沟通。在content.cljs 我有:
(defn init []
(go
(let [bg (runtime/connect)]
(console/log "content script test")
(while true
(>! bg :lol-i-am-a-content-script)
(console/log "Background said: " (<! bg))))))
在background.cljs:
(defn on-connect-listener []
(console/log "on-connect-listener")
(go-loop
[channel (runtime/on-connect)]
(let [content (<! channel)]
(console/log "Content script said: " (<! content))
(>! content :fml-i-am-the-background-script)
(recur channel))))
(定义初始化 [] (on-connect-listener))
在 Chrome 控制台中,我只收到“后台说:fml-i-am-the-background-script”消息,因此只有后台发送到内容页面的消息,反之亦然(我本来希望“内容脚本说:lol-i-am-a-content-script")。
很可能我在这里犯了一些明显的错误。有人可以帮忙吗?
谢谢!
【问题讨论】:
-
你能展示任何尝试以及它们是如何失败的吗?
-
@Xan - 扩展了我原来的问题。谢谢!
标签: google-chrome-extension clojurescript