从Javascript调用Google Chrome扩展程序 [英] Invoking a Google Chrome extension from Javascript
问题描述
有一个很好的扩展程序,称为 Blipshot 这需要页面截图。我需要调用页面级JavaScript的扩展,而不是点击它的图标。这是可能的吗?
您无法在网页中调用任何扩展方法。但是,可以将内容脚本注入到网页中,并使用 sendMessage
和 onMessage
或 onConnect
和 connect
。
编辑扩展程序:访问 chrome:// extensions
页面,并启用开发者模式。解压扩展名和/或访问扩展名的目录。编辑 manifest.json
文件,并添加必要的行(参见 here )。
在后台页面添加一个事件监听器。在内容脚本中添加一个轮询器,例如:
//内容脚本
var poller = window.setInterval(function (){
if(document.documentElement.getAttribute('extensionCalled')){
chrome.extension.sendMessage({anyname:anything},function(){
/ *可选的回调函数* / alert(发生了什么事)
});
clearInterval(poller);
}
},200);
//后台
chrome.extension.onMessage.addListener(函数(request,sender,callback){
if(request.anyname ==anything){
function_logic_here();
//可选,回调:
callback();
}
});
参见
- Chrome扩展程序 - 检索Gmail的原始邮件 - 使用DOM事件在页面和扩展程序之间进行通信(推荐) li>
- MDN:
postMessage
code> - 它可以用于在页面和扩展之间进行通信(当页面本身也使用 - < a href =http://code.google.com/chrome/extensions/messaging.html =nofollow noreferrer>扩展消息传递
- 内容脚本
- 扩展中的内容脚本
消息
事件时,此方法可能会导致冲突)。参考文献:
There is an excellent extension called Blipshot which takes page screenshots. I need to invoke the extension with page level javascript, instead of clicking its icon. Is this possible?
You cannot invoke any methods of an extension from within a web page. However, it's possible to inject a content script into the web page, and use sendMessage
and onMessage
, or onConnect
and connect
.
To edit an extension: Visit chrome://extensions
page, and enable the Developer mode. Unpack an extension and/or visit the extension's directory. Edit the manifest.json
file, and add the necessary lines (see here).
Add an event event listener at the background page. Add a poller in the content script, eg:
// Content script
var poller = window.setInterval(function() {
if (document.documentElement.getAttribute('extensionCalled')) {
chrome.extension.sendMessage({"anyname": "anything"}, function() {
/*optional callback function.*/alert("Something happened")
});
clearInterval(poller);
}
}, 200);
// Background
chrome.extension.onMessage.addListener(function(request, sender, callback) {
if (request.anyname == "anything") {
function_logic_here();
//Optionally, callback:
callback();
}
});
See also
- Chrome extension - retrieving Gmail's original message - Using DOM events to communicate between a page and extension (recommended)
- MDN:
postMessage
- It can be used to communicate between a page and extension (this method may cause conflicts when the page itself is also using themessage
events).
References:
这篇关于从Javascript调用Google Chrome扩展程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!