Invoking a Google Chrome extension from Javascript

感情迁移 提交于 2019-12-18 17:28:36

问题


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?


回答1:


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 the message events).

References:

  • Extension messaging
  • Content scripts
  • Content scripts in extensions



回答2:


It would only be possible if the extension provides an interface to do it. Extensions run in an isolated environment, so you don't have direct access to any of their functions.

The closest they get is content scripts, which have access to the DOM. Because of that, you can communicate using events, but obviously the extension would need to set up event handlers for them, so it completely depends on the extension.



来源:https://stackoverflow.com/questions/7597310/invoking-a-google-chrome-extension-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!