简体   繁体   English

从chrome扩展中注入函数/变量以进行分页

[英]Inject functions/variables to page from a chrome extension


I'm writing a Chrome Extension that adds functionality to certain pages a user visits. 我正在编写一个Chrome扩展程序,可为用户访问的某些页面添加功能。
To do that, I'll need to inject a few variables and functions that the page needs to be able to call. 为此,我需要注入一些页面需要能够调用的变量和函数。
These variables/functions are generated in a content script. 这些变量/函数在内容脚本中生成。

However, since content scripts run in a secluded environment, the host page can not access it. 但是,由于内容脚本在隐蔽环境中运行,因此主机页无法访问它。

According to this article: http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication it is possible for content script and host page to communicate through the DOM by adding events. 根据这篇文章: http//code.google.com/chrome/extensions/content_scripts.html#host-page-communication ,内容脚本和主机页面可以通过添加事件来通过DOM进行通信。
But that's a horrible way to do things, and I'd really like to see some way to inject methods/variables easily. 但这是一种可怕的做事方式,我真的很想看到一些方法来轻松注入方法/变量。

Is there such a possibility? 有可能吗?

Thanks! 谢谢!

If it still interests anybody, I've found a solution communicating between content script and page itself through messages. 如果它仍然感兴趣的话,我找到了一个解决方案,通过消息在内容脚本和页面本身之间进行通信。

Something like this on the sending script: 发送脚本上有这样的东西:

window.postMessage({ type: "messageType", params: { param: "value", anotherParam: "value" } }, "*"/*required!*/);

And then on the receiving script do something like this: 然后在接收脚本上执行以下操作:

window.addEventListener("message", function(event) {
        // We only accept messages from ourselves
        if (event.source != window)
            return;

        switch (event.data.type) {
        case "blabla":
            // do blabla
            // you can use event.data.params to access the parameters sent from page.
            break;
        case "another blabla":
            // do another blabla 
            break;
        }
    });

Here's how I coded it on my extension, http://pagexray.com/extension/ 这是我在我的扩展程序上编码的方式, http://pagexray.com/extension/

on your manifest.json 在你的manifest.json上

 "content_scripts": [
    {
        "matches": ["http://*/*"],
        "js": ["script.js"]
    }
],

on your script.js 在你的script.js上

(function(){
  var script = document.createElement('script');
  script.src = "http://example.com/external.js";
  script.addEventListener('load', function() { });
  document.head.appendChild(script);
})();

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

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