69

如何将参数传递给使用以下方式注入的内容脚本文件中的 JavaScript:

chrome.tabs.executeScript(tab.id, {file: "content.js"});
4

3 回答 3

122

没有“将参数传递给文件”之类的东西。

可以做的是在执行文件之前插入内容脚本,或者在插入文件发送消息。我将在下面展示这些不同方法的示例。

在执行JS文件之前设置参数

如果要在插入文件之前定义一些变量,只需嵌套chrome.tabs.executeScript调用:

chrome.tabs.executeScript(tab.id, {
    code: 'var config = 1;'
}, function() {
    chrome.tabs.executeScript(tab.id, {file: 'content.js'});
});

如果您的变量不是那么简单,那么我建议使用JSON.stringify将对象转换为字符串:

var config = {somebigobject: 'complicated value'};
chrome.tabs.executeScript(tab.id, {
    code: 'var config = ' + JSON.stringify(config)
}, function() {
    chrome.tabs.executeScript(tab.id, {file: 'content.js'});
});

使用前面的方法,可以通过content.js以下方式使用变量:

// content.js
alert('Example:' + config);

JS文件执行后设置参数

可以使用前面的方法在 JS 文件后设置参数。您可以使用消息传递 API来传递参数,而不是直接在全局范围内定义变量:

chrome.tabs.executeScript(tab.id, {file: 'content.js'}, function() {
    chrome.tabs.sendMessage(tab.id, 'whatever value; String, object, whatever');
});

在内容脚本 ( content.js) 中,您可以使用事件监听这些消息chrome.runtime.onMessage,并处理这些消息:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // Handle message.
    // In this example, message === 'whatever value; String, object, whatever'
});
于 2013-07-11T10:40:26.330 回答
26

有五种通用方法可以将数据传递给使用( MDN )注入的内容脚本:tabs.executeScript()

  • 在注入脚本 之前设置数据
    1. 使用( MDN )传递数据(在注入脚本之前设置)。chrome.storage.local
    2. 在设置数据变量的脚本之前注入代码(有关可能的安全问题,请参阅详细讨论)。
    3. 为要注入内容脚本的域设置一个 cookie。此方法还可用于将数据传递给manifest.json注入document_start的内容脚本,而无需内容脚本执行异步请求。
  • 注入脚本 发送/设置数据
    1. 注入脚本,使用消息传递( MDN )传递数据。
    2. 在您的内容脚本中使用( MDN )来侦听后台脚本以使用( MDN )设置值。chrome.storage.onChangedchrome.storage.local.set()

使用chrome.storage.local(在执行脚本之前设置)

使用此方法可维护您正在使用的执行范例,即注入执行功能然后退出的脚本。它也没有使用动态值来构建执行代码的潜在安全问题,这是在下面的第二个选项中完成的。

从您的弹出脚本中:

  1. 使用( MDN )存储数据。chrome.storage.local.set()
  2. 在回调中chrome.storage.local.set(),调用MDNtabs.executeScript()
var updateTextTo = document.getElementById('comments').value;
chrome.storage.local.set({
    updateTextTo: updateTextTo
}, function () {
    chrome.tabs.executeScript({
        file: "content_script3.js"
    });
});

从您的内容脚本:

  1. 从( MDN )读取数据。chrome.storage.local.get()
  2. 对 DOM 进行更改。
  3. 使数据无效storage.local(例如删除密钥:MDN)。chrome.storage.local.remove() 
chrome.storage.local.get('updateTextTo', function (items) {
    assignTextToTextareas(items.updateTextTo);
    chrome.storage.local.remove('updateTextTo');
});
function assignTextToTextareas(newText){
    if (typeof newText === 'string') {
        Array.from(document.querySelectorAll('textarea.comments')).forEach(el => {
            el.value = newText;
        });
    }
}

参见:注释 1 和 2。

在脚本之前注入代码以设置变量

在执行脚本之前,您可以注入一些代码,在内容脚本上下文中设置一个变量,然后您的主脚本可以使用该变量:

安全问题:

以下用于"'" + JSON.stringify().replace(/\\/g,'\\\\').replace(/'/g,"\\'") + "'"将数据编码为文本,当将其解释为代码时,该文本将是正确的 JSON,然后将其放入code字符串中。这些.replace()方法需要 A) 在用作代码时将文本正确解释为字符串,并且 B) 引用'数据中存在的任何内容。然后它JSON.parse()用于将数据返回到内容脚本中的字符串。虽然这种编码不是严格要求的,但这是一个好主意,因为您不知道要发送到内容脚本的值的内容。这个值很容易会破坏您正在注入的代码(即用户可能正在使用'和/或"在他们输入的文本中)。如果您不以某种方式转义该值,则存在可能导致执行任意代码的安全漏洞。

从您的弹出脚本中:

  1. 注入一段简单的代码,设置一个变量来包含数据。
  2. ( MDN )的回调中,调用注入你的脚本(注意:将按照你调用的顺序执行脚本,只要它们具有相同的值。因此,等待小的回调不是严格要求的)。chrome.tabs.executeScript()tabs.executeScript()tabs.executeScript()tabs.executeScript()runAtcode
var updateTextTo = document.getElementById('comments').value;
chrome.tabs.executeScript({
    code: "var newText = JSON.parse('" + encodeToPassToContentScript(updateTextTo) + "');"
}, function () {
    chrome.tabs.executeScript({
        file: "content_script3.js"
    });
});

function encodeToPassToContentScript(obj){
    //Encodes into JSON and quotes \ characters so they will not break
    //  when re-interpreted as a string literal. Failing to do so could
    //  result in the injection of arbitrary code and/or JSON.parse() failing.
    return JSON.stringify(obj).replace(/\\/g,'\\\\').replace(/'/g,"\\'")
}

从您的内容脚本:

  1. 使用存储在变量中的数据对 DOM 进行更改
if (typeof newText === 'string') {
    Array.from(document.querySelectorAll('textarea.comments')).forEach(el => {
        el.value = newText;
    });
}

请参阅:注释 1、2 和 3。

使用消息传递MDN (在内容脚本注入发送数据)

这需要您的内容脚本代码为弹出窗口或后台脚本(如果与 UI 的交互导致弹出窗口关闭)发送的消息安装侦听器。它有点复杂。

从您的弹出脚本中:

  1. 使用( MDN )确定活动选项卡。tabs.query()
  2. 呼叫( MDN )tabs.executeScript()
  3. 在 for 的回调中tabs.executeScript(),使用( MDN )(需要知道)将数据作为消息发送。tabs.sendMessage()tabId
var updateTextTo = document.getElementById('comments').value;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.executeScript(tabs[0].id, {
        file: "content_script3.js"
    }, function(){
        chrome.tabs.sendMessage(tabs[0].id,{
            updateTextTo: updateTextTo
        });
    });
});

从您的内容脚本:

  1. 使用( MDN )添加侦听器。chrome.runtime.onMessage.addListener()
  2. 退出您的主代码,让监听器保持活动状态。如果您愿意,您可以返回一个成功指示器。
  3. 收到带有数据的消息后:
    1. 对 DOM 进行更改。
    2. 移除你的runtime.onMessage听众

#3.2 是可选的。您可以让您的代码保持活动状态以等待另一条消息,但这会将您使用的范例更改为您加载代码并保持驻留等待消息启动操作的范例。

chrome.runtime.onMessage.addListener(assignTextToTextareas);
function assignTextToTextareas(message){
    newText = message.updateTextTo;
    if (typeof newText === 'string') {
        Array.from(document.querySelectorAll('textarea.comments')).forEach(el => {
            el.value = newText;
        });
    }
    chrome.runtime.onMessage.removeListener(assignTextToTextareas);  //optional
}

参见:注释 1 和 2。


注意 1:Array.from()如果您没有多次使用并且使用具有它的浏览器版本(Chrome >= 版本 45,Firefox >= 32),则使用很好。在 Chrome 和 Firefox 中,Array.from()与从 NodeList 获取数组的其他方法相比,速度较慢。为了更快、更兼容地转换为数组,您可以使用此答案asArray()中的代码。该答案中提供的第二个版本也更强大。asArray()

注意 2:如果您愿意将代码限制为 Chrome 版本 >= 51 或 Firefox 版本 >= 50,Chrome从 v51 开始提供NodeListsforEach()方法。因此,您不需要转换为数组。显然,如果您使用不同类型的循环,则不需要转换为数组。

注 3:虽然我之前在自己的代码中使用过这种方法(使用变量值注入脚本),但我被提醒在阅读此答案时应该将其包含在此处。

于 2016-11-26T06:08:07.303 回答
4

您可以使用该args属性,请参阅此文档

const color = getUserColor();
function changeBackgroundColor(backgroundColor) {
  document.body.style.backgroundColor = backgroundColor;
}
const tabId = getTabId();
chrome.scripting.executeScript(
    {
      target: {tabId: tabId},
      func: changeBackgroundColor,
      args: [color],
    },
    () => { ... });

编辑:我的错误 - 这仅适用于注入函数,而不是问题指定的文件。

于 2021-10-09T15:01:55.790 回答