简体   繁体   English

将chrome扩展名迁移到清单2-脚本注入

[英]migrating chrome extension to manifest 2 - script injection

I'm trying to migrate my Chrome extension to manifest 2. The current version uses a background.html page that is basically one big script tag. 我正在尝试将我的Chrome扩展程序迁移到清单2。当前版本使用的background.html页面基本上是一个大脚本标记。 Since that is no longer possible, I switched to using a background.js script and after much search and experiments, still failing to inject a script from an external file. 由于这不再可行,因此我转而使用background.js脚本,经过大量搜索和实验后,仍然无法从外部文件中插入脚本。 In the current version I just use document.write to inject a script tag that will run when the browser loads and I haven't found a way to do this now. 在当前版本中,我只是使用document.write注入一个脚本标签,该标签将在浏览器加载时运行,而我现在还没有找到一种方法。

I'm aware of the chrome.tabs.onUpdated.addListener function and the ability to inject script per tab update using a XMLHttpRequest object, but the script I want to run should do so only when the browser loads. 我知道chrome.tabs.onUpdated.addListener函数以及使用XMLHttpRequest对象为每个选项卡更新注入脚本的能力,但是我要运行的脚本仅在加载浏览器时才这样做。

current code (in a script tag in a background.html file): 当前代码(在background.html文件中的脚本标签中):

document.write("<script type='text/javascript' src='" + url + "'></script>");

In the background.js file this now leads to an error: Refused to load the script 'http://www.mydomain.com/script.js' because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". 现在,在background.js文件中会导致错误:拒绝加载脚本“ http://www.mydomain.com/script.js”,因为它违反了以下内容安全策略指令:“ script-src'self' chrome-extension-resource:”。

I've tried all sorts of code, including: 我尝试了各种代码,包括:

var s = document.createElement('script');
s.src = chrome.extension.getURL(url);
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);

But seems like this will work only for local script files whereas I need to load an external online file. 但似乎这仅适用于本地脚本文件,而我需要加载外部在线文件。

The error you are getting is due the directive content_security_policy in the manifest. 您得到的错误是由于清单中的指令content_security_policy引起的。 You need to specify the domain of your script as part of it. 您需要在其中指定脚本的域。 Here's an example for jQuery: 这是jQuery的示例:

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"

And in the Background.html page 并在Background.html页面中

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

This didn't cause me any error. 这没有引起我任何错误。 About to when download this script, that's up to your extension architecture, but there's many ways you can tell your application how to do it. 关于何时下载此脚本,这取决于您的扩展体系结构,但是您可以通过多种方式告诉您的应用程序该怎么做。 Remember that the first thing your application loads is your Background page, so you can do send a message from your Background page to your content script when it's loaded. 请记住,您的应用程序加载的第一件事是“背景”页面,因此您可以在加载时将消息从“背景”页面发送到内容脚本。 Example: 例:

/**
* Listener for Displaying the Extension Page Action when the Tab is updated.
* @private
* @event displayPageAction
* @param {Number} tabId The tabId given by the tabs listener to know which tab was updated.
* @param {Object} changeInfo The current status of the tab.
* @param {Object} tab The metadata of the tab.
**/
var displayPageAction = function (tabId, changeInfo, tab) {
    var match = regexAIESEC.exec(tab.url); // var regexAIESEC = new RegExp(/http:\/\/www.myaiesec.net\//);
    // We only display the Page Action if we are inside a MyAIESEC Tab.
    if(match && changeInfo.status == 'complete') {
        //We send the proper information to the content script to render our app.
         chrome.tabs.sendMessage(tab.id, {load: true}, function(response) {
            if(response) {
                //After successfully getting the response, we show the Page Action Icon.
                chrome.pageAction.show(tab.id);     
            }
        });
    }
};

This is an example of when to show a Page action after the tabs was updated. 这是更新选项卡后何时显示“页面”操作的示例。 In a previous code: 在之前的代码中:

chrome.tabs.onUpdated.addListener(displayPageAction);

You can read more about Content Security Policy for Chrome Extensions here and more about Message Passing here . 你可以阅读更多有关内容安全策略的Chrome扩展在这里 ,更多的是消息传递在这里

a) document.write("<script type='text/javascript' src='" + url + "'></script>"); a) document.write("<script type='text/javascript' src='" + url + "'></script>"); will not work in background.js because your document is document of background page.Refer documentation and architecture background.js中将无法使用,因为您的document是背景页面的文档 。请参阅文档体系结构

b) chrome.extension.getURL(url); b) chrome.extension.getURL(url); retrieves relative url of file, you can try tabs API instead 检索文件的相对URL,您可以尝试使用Tabs API

I was able to inject a Jquery to any arbitrary page with following code, do you have permissions set correctly? 我可以使用以下代码将Jquery插入任意页面,您是否正确设置了权限?

References 参考文献

a) Content Scripts a) 内容脚本

b) Manifest Version 2 b) 清单版本2

c) tabs API c) 标签API

d) Background Pages d) 背景页面

manifest.json manifest.json

{
"name":"Script Injection Demo",
"description":"This demonstrates Script Injection",
"version":"1",
"manifest_version":2,
"content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["myscript.js"]
    }
  ]
}

myscript.js myscript.js

//Creating a Script Tag
var _scriptTag = document.createElement('script');
//Referencing external URL
_scriptTag.src='https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.js';
//Appending child
(document.head||document.documentElement).appendChild(_scriptTag);

Let me know if this sort of injection does not work for you. 让我知道这种注射是否对您不起作用。

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

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