简体   繁体   English

如何从任何页面的JavaScript访问谷歌浏览器扩展程序

[英]How to access google chrome extension from any page's javascript

I am trying to figure out how can I call into my extension from a normal web page. 我试图找出如何从普通网页调用我的扩展程序。 All documentation that I find seems to be either for communication between extensions, or between content scripts and extensions. 我发现的所有文档似乎都是用于扩展之间的通信,或者是内容脚本和扩展之间的通信。

Any pointers are much appreciated! 任何指针都非常感谢!

I think you should make a content script, that injects an object into your page that calls your extension. 我认为你应该创建一个内容脚本,将一个对象注入到调用扩展的页面中。

Create a content script that injects YourExt.js into every page, which should contain: 创建一个内容脚本,将YourExt.js注入每个页面,其中应包含:

var YourExt = {
doThis: function () {
    chrome.extension.sendRequest('doThis');
},
doThat: function () {
    chrome.extension.sendRequest({
        action: 'doThat',
        params: ['foo','bar']
    });
}
}

While extensions can't access page variables and vice versa, you can communicate between page and extension through events. 虽然扩展无法访问页面变量,反之亦然,您可以通过事件在页面和扩展之间进行通信。 Here is a quick example of creating custom events: 以下是创建自定义事件的快速示例:

function fireEvent(name, target) {
    //Ready: create a generic event
    var evt = document.createEvent("Events")
    //Aim: initialize it to be the event we want
    evt.initEvent(name, true, true); //true for can bubble, true for cancelable
    //FIRE!
    target.dispatchEvent(evt);
}

function foobar() {
    alert("foobar");
}

function testEvents() {
    window.addEventListener("foobar", foobar, false); //false to get it in bubble not capture.
    fireEvent("foobar", document);
}

(taken from here ) (取自这里

So if you need to pass information from a page to an extension, you would need to fire a custom event on a page which you will be listening to in your content script. 因此,如果您需要将信息从页面传递到扩展,则需要在您将在内容脚本中监听的页面上触发自定义事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM