简体   繁体   English

如何通过Chrome扩展程序将某些文件注入某些网站

[英]How do I inject certain files into certain websites from a chrome extension

In my chrome extension I have multiple files that inject script into websites, I want to know how I can inject 1 file for a certain website. 在我的chrome扩展程序中,我有多个将脚本注入网站的文件,我想知道如何为某个网站注入1个文件。 To better explain 为了更好的解释

My chrome extension has 1 file to inject into Github and another file to inject into a different website how would I inject each one into there own website without having both files injecting into each website. 我的chrome扩展程序有1个文件要注入到Github中,而另一个文件要注入到另一个网站中,我如何将每个文件都注入到自己的网站中, 而又没有将两个文件都注入到每个网站中。 So each file will be injected into there own website. 因此,每个文件都将注入到自己的网站中。

Injecting JavaScript files is done either through an entry in the content_scripts key in your manifest.json , or through chrome.tabs.executeScript() . 可以通过manifest.jsoncontent_scripts键中的条目或通过chrome.tabs.executeScript()注入JavaScript文件。

Using chrome.tabs.executeScript() 使用chrome.tabs.executeScript()

You should use chrome.tabs.executeScript() if you don't need your script injected every single time the matching URL is loaded. 如果您不需要每次加载匹配的URL时都注入脚本,则应使用chrome.tabs.executeScript() This is particularly the case when interaction with your extension begins with the user clicking on a browserAction , or pageAction button. 当与扩展程序的交互始于用户单击browserActionpageAction按钮时, pageAction

Given that chrome.tabs.executeScript() is a direct JavaScript API call, I am going to assume that you understand how to make a choice as to what to inject based on the URL from the tab.url property. 假设chrome.tabs.executeScript()是直接的JavaScript API调用,我将假设您了解如何根据tab.url属性中的URL来选择要注入的tab.url

Injecting stackContent.js could look like: 注入stackContent.js可能类似于:

chrome.tabs.executeScript(tabId,{
    file: "stackContent.js"
}, result => {
    handleExecuteScriptAndInsertCSSErrors(tabId);
});

Injecting both jquery.js and stackContent.js could look like: 注入jquery.jsstackContent.js可能看起来像:

chrome.tabs.executeScript(tabId,{
    file: "jquery.js"
}, result1 => {
    handleExecuteScriptAndInsertCSSErrors(tabId);
    chrome.tabs.executeScript(tabId,{
        file: "stackContent.js"
    }, result2 => {
        handleExecuteScriptAndInsertCSSErrors(tabId);
    });
});

You should also be checking for errors reported by chrome.runtime.lastError . 您还应该检查chrome.runtime.lastError报告的chrome.runtime.lastError A function I use for doing so in both Chrome and Firefox WebExtensions is: 我在Chrome和Firefox WebExtensions中都使用的功能是:

function handleExecuteScriptAndInsertCSSErrors(tabId) {
    if(chrome.runtime.lastError) {
        let message = chrome.runtime.lastError.message;
        let isFirefox = !!window.InstallTrigger;
        let extraMessage = tabId ? 'in tab ' + tabId + '.' : 'on this page.';
        if((!isFirefox && message.indexOf('Cannot access a chrome:') > -1) //Chrome
            || (isFirefox && message.indexOf('No window matching') > -1) //Firefox
        ) {
            //The current tab is one into which we are not allowed to inject scripts.
            //  This is most likely because we are injecting based on a action button
            //  click. You should disable the action button when a tab is active on
            //  which you can not perform the task that is expected by the user.
            let messageText= 'This extension, ' + chrome.runtime.id
                             + ', does not work ' + extraMessage;
            //alert(messageText); //Use for testing
            console.log(messageText);
        } else {
            //Report the error
            if(isFirefox) {
                //In Firefox, runtime.lastError is an Error Object including a stack trace.
                console.error(chrome.runtime.lastError);
            } else {
                console.error(message);
            }
        }
    }
}

Using the content_scripts key in manifest.json manifest.json中使用content_scripts

In your manifest.json you have a content_scripts key which describes scripts or CSS that are always injected into matching URLs. manifest.json中,您有一个content_scripts键,该键描述始终插入匹配URL的脚本或CSS。 You should use this if you need a script, or CSS to be always injected into matching URLs. 如果需要脚本或CSS 始终插入匹配的URL,则应使用此选项。

While it might be more convenient to always have your script injected, you should seriously consider not doing so unless it is needed . 尽管始终注入脚本可能更方便,但是您应该认真考虑不要这样做,除非需要它。 You should particularly stay away from doing so if you are loading large scripts and/or on a large number of websites (eg all URLs). 如果要加载大型脚本和/或在大量网站(例如所有URL)上,则应特别避免这样做。 Indiscriminately injecting your script(s) (including libraries) on a large number of websites can take significant resources on the user's computer which can cause a loss of performance, affecting user experience. 不加选择地将脚本(包括库)注入大量网站可能会占用用户计算机上的大量资源,这可能会导致性能下降,从而影响用户体验。 If you need to have interaction begin from within the website, try loading a smaller script that waits for that interaction to begin, then messages your background script to inject the rest of your functionality. 如果需要从网站内部进行交互,请尝试加载一个较小的脚本,等待该交互开始,然后向您的后台脚本发送消息,以注入其余功能。 Sometimes you do need your script loaded all the time, but try to think about it from your user's perspective, not just what is convenient in writing your extension. 有时您确实需要一直加载脚本,但是请尝试从用户的角度考虑脚本,而不仅仅是编写扩展的方便之处。 As an example of going too far injecting scripts using content_scripts , the extension about which this question was asked injects 78 different scripts into every https:// page. 举一个使用content_scripts注入脚本的例子, 该问题的扩展名将78个不同的脚本注入到每个 https://页面中。

The content_scripts key contains an array of objects. content_scripts键包含一个对象数组。 Each object describes a single injection directive. 每个对象描述一个注射指令。 The object can contain multiple conditions and multiple files, but each one is all-or-nothing; 该对象可以包含多个条件和多个文件,但是每个对象要么全有要么全无。 either all files described in that object are injected, or none, depending on if the URL matches. 根据URL是否匹配,注入该对象中描述的所有文件,还是不注入。 If you want some file(s) injected to some URLs and some other file(s) injected to other URLs, then you use separate Objects to describe each group. 如果要将某些文件注入到某些URL,而将某些其他文件注入到其他URL,则可以使用单独的对象来描述每个组。

An example, which injects jquery.js & stackContent.js into Stack Exchange sites and jquery.js & exampleContent.js into example.com is: jquery.jsstackContent.js注入Stack Exchange网站并将jquery.jsexampleContent.js注入example.com的示例是:

"content_scripts": [
    {
        "matches": [
            "http*://*.askubuntu.com/*",
            "http*://*.mathoverflow.net/*",
            "http*://*.serverfault.com/*",
            "http*://*.stackapps.com/*",
            "http*://*.stackexchange.com/*",
            "http*://*.stackoverflow.com/*",
            "http*://*.superuser.com/*"
        ],
        "js": ["jquery.js", "stackContent.js"]
    },
    {
        "matches": ["http*://*.example.com/*"],
        "js": ["jquery.js", "exampleContent.js"]
    }
]

Permissions 权限

Depending on what you are doing, you are going to need permissions to interact with the matching URLs you are interested in and/or use chrome.tabs . 根据您的操作,您将需要权限才能与您感兴趣的匹配URL进行交互和/或使用chrome.tabs From the above examples: 从以上示例:

"permissions": [
    "tabs",
    "http*://*.askubuntu.com/*",
    "http*://*.mathoverflow.net/*",
    "http*://*.serverfault.com/*",
    "http*://*.stackapps.com/*",
    "http*://*.stackexchange.com/*",
    "http*://*.stackoverflow.com/*",
    "http*://*.superuser.com/*",
    "http*://*.example.com/*"
]

Use the Tampermonkey / Greasemonkey extensions, with the header like that: 使用Tampermonkey / Greasemonkey扩展名,标题如下:

// ==UserScript==
// @name         MTV Statistical Data For Tampermonkey & Greasemonkey
// @namespace    MTV_statistical_data
// @include     /^https?://(www\.)?mytrafficvalue\.com/shareholders\.html(\#marketplace)?$/
// @author       facebook.com/igor39
// @version      7.5
// @grant        none
// @description  Improving the user experience & provide more of statistics on the page www.mytrafficvalue.com/shareholders.html
// ==/UserScript==

Example: http://pastebin.com/Z4zq2h6Q 示例: http//pastebin.com/Z4zq2h6Q

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

相关问题 Chrome 扩展程序:如何将 CSS 和 Javascript 注入某个 URL? - Chrome Extension: How do I inject CSS and Javascript into a certain URL? 如何限制上下文菜单仅针对Chrome扩展程序中的特定选定文字显示? - How do I restrict context menus to appear only for certain selected text in a Chrome extension? Chrome 扩展程序:如何注入用户提供的脚本? - Chrome Extension: How do I inject a script that the user provided? chrome extension:如何将某些标签中的所有音频静音 - chrome extension: how to mute all audio from certain tab 如何将大量Javascript文件注入到CHROME扩展中? - How to inject lots of Javascript files into CHROME EXTENSION? 从 xml 解析某些文本的 Chrome 扩展 - Chrome extension that parses certain text from xml Chrome扩展程序:如何获取内容脚本扩展程序以显示在某些网站上 - Chrome Extension: How do I get me Content Script Extension to show up on select websites 如何重新加载chrome扩展中的某些选项卡 - How to reload certain tab in chrome extension Chrome Devtools控制台无法在某些网站中使用 - Chrome Devtools console not working in certain websites 如何使用 InboxSDK 在 Gmail 和其他网站上运行 chrome 扩展? - How do I make a chrome extension with InboxSDK run both on Gmail and on other websites?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM