从Javascript调用Google Chrome扩展程序 [英] Invoking a Google Chrome extension from Javascript

查看:745
本文介绍了从Javascript调用Google Chrome扩展程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个很好的扩展程序,称为 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> - 它可以用于在页面和扩展之间进行通信(当页面本身也使用消息事件时,此方法可能会导致冲突)。


    参考文献:




    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

    References:

    这篇关于从Javascript调用Google Chrome扩展程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆