我的 Chrome 扩展程序使用消息传递从后台页面上扩展程序的内置本地存储区域检索各种值。
我喜欢 chrome 消息传递的一点是,它允许您在 sendMessage 调用中包含一个回调函数,如下所示:
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
相应的消息接收代码如下所示(来自 Chrome 扩展文档的示例代码):
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
我正在尝试将我的扩展程序转换为 Safari 扩展程序格式,但我不知道如何将 Chrome 的 sendMessage/onMessage 函数映射到 Safari 的
safari.self.tab.dispatchMessage(name, data) 消息处理函数
甚至可以在 Safari 的 dispatchMessage 函数调用中包含回调函数吗? 如果没有,我应该如何解决这个限制?
最佳答案
在只提供单向消息传递系统的环境中,您始终可以自己实现“消息回调”,方法是将唯一 ID 与每条消息相关联,并将回调存储在将这些 ID 映射到的字典中回调。
在这个答案的最后,我从我的跨浏览器的源代码中复制粘贴了 Safari 特定的存储模块 Lyrics Here extension ,它提供了以下 API:
config.getItem(key, callback)config.setItem(key, value, callback)config.removeItem(key, callback)config.clear(回调)getItem 的回调包含与键关联的值(如果找到)。其他回调接收一个 bool 值,指示操作是否成功。
源代码带有注释并包含处理一些边缘情况的片段。如果有任何不清楚的地方,请随时向我提问。
// Adapter for maintaining preferences (Safari 5+)
// All methods are ASYNCHRONOUS
define('config-safari', function() {
var config = {};
var callbacks = {};
['getItem', 'setItem', 'removeItem', 'clear'].forEach(function(methodName) {
config[methodName] = function() {
var args = [].slice.call(arguments);
var callback = args.pop();
var messageID = Math.random();
callbacks[messageID] = callback;
var message = {
type: methodName,
messageID: messageID,
args: args
};
safari.self.tab.dispatchMessage('config-request', message);
};
});
config.init = function() {
if (typeof safari === 'undefined') {
// Safari bug: safari is undefined when current context is an iframe
// and src="javascript:''"
// This error is only expected on YouTube.
// config.getItem is triggered in main, so we just redefine
// it. Don't overwrite setItem, etc., so that errors are thrown
// when these methods are used.
config.getItem = function(key, callback){
callback();
};
return;
}
safari.self.addEventListener('message', function(event) {
if (event.name === 'config-reply') {
var messageID = event.message.messageID;
var callback = callbacks[messageID];
// Check if callback exists. It may not exist when the script is
// activated in multiple frames, because every frame receives the message
if (callback) {
delete callbacks[messageID];
callback(event.message.result);
}
}
}, true);
};
return config;
});
global.html 片段:
<script>
(function(exports) {
var config = {};
config.getItem = function(key, callback) {
var result = safari.extension.settings.getItem(key);
if (typeof result === 'string') {
try {
result = JSON.parse(result);
} catch (e) {
// Extremely unlikely to happen, but don't neglect the possibility
console.log('config.getItem error: ' + e);
result = undefined;
}
}
callback(result);
};
// callback's argument: true on success, false otherwise
config.setItem = function(key, value, callback) {
var success = false;
try {
value = JSON.stringify(value);
// Safari (5.1.5) does not enforce the database quota,
// let's enforce it manually (ok, set the quota per key, since
// the performance issue only occur when a specific key has an outrageous high value)
// 1 MB should be sufficient.
if (value.length > 1e6) {
throw new Error('QUOTA_EXCEEDED_ERR: length=' + value.length);
}
safari.extension.settings.setItem(key, value);
success = true;
} catch (e) {
console.log('config.setItem error: ' + e);
}
callback(success);
};
// callback's argument: true on success, false otherwise
config.removeItem = function(key, callback) {
safari.extension.settings.removeItem(key);
callback(true);
};
// callback's argument: true on success, false otherwise
config.clear = function(callback) {
safari.extension.settings.clear();
callback(true);
};
// config's message handler
function handleConfigRequest(event) {
var args = event.message.args;
// Last argument: Always a callback
args.push(function(result) {
// Note: All of the config methods send a callback only once
// Behavior for calling the callback twice is undefined.
// Send a reply to trigger the callback at the sender's end
event.target.page.dispatchMessage('config-reply', {
messageID: event.message.messageID,
result: result
});
});
config[event.message.type].apply(config, args);
}
// Export
exports.handleConfigRequest = handleConfigRequest;
})(window);
</script>
<script>
safari.application.addEventListener('message', function(event) {
switch (event.name) {
case 'config-request':
handleConfigRequest(event);
break;
/* ... other things removed ... */
}
}, true);
</script>
关于javascript - 是否有一种简单的转换方法可以将 chrome 消息传递转换为 safari 消息传递语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20583309/
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c