首页  >  文章  >  web前端  >  如何将参数传递给 Chrome 扩展中的注入内容脚本?

如何将参数传递给 Chrome 扩展中的注入内容脚本?

Barbara Streisand
Barbara Streisand原创
2024-10-27 16:22:01252浏览

How do I pass parameters to injected content scripts in Chrome extensions?

向注入的内容脚本传递参数

使用 chrome.tabs.executeScript() 注入内容脚本时,可能会需要向脚本传递参数。然而,澄清“向文件传递参数”不是一个适用的概念至关重要。

相反,有两个选项需要考虑:在脚本执行之前或之后设置参数。

在执行前设置参数

您可以通过嵌套 chrome.tabs.executeScript 调用来注入具有预定义参数的内容脚本:

<code class="javascript">chrome.tabs.executeScript(tab.id, {
    code: 'var config = 1;'
}, function() {
    chrome.tabs.executeScript(tab.id, {file: 'content.js'});
});</code>

对于复杂参数,请使用 JSON.stringify:

<code class="javascript">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'});
});</code>

在 content.js 中:

<code class="javascript">// content.js
alert('Example:' + config);</code>

执行后设置参数

也可以在脚本执行后使用消息传递来设置参数:

<code class="javascript">chrome.tabs.executeScript(tab.id, {file: 'content.js'}, function() {
    chrome.tabs.sendMessage(tab.id, 'whatever value; String, object, whatever');
});</code>

在 content.js 中:

<code class="javascript">chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // Handle message.
    // In this example, message === 'whatever value; String, object, whatever'
});</code>

以上是如何将参数传递给 Chrome 扩展中的注入内容脚本?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn