将参数传递给使用chrome.tabs.executeScript()注入的内容脚本 [英] Pass a parameter to a content script injected using chrome.tabs.executeScript()

查看:5508
本文介绍了将参数传递给使用chrome.tabs.executeScript()注入的内容脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I pass a parameter to the JavaScript in a content script file which is injected using:

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


推荐答案

一个文件。

您可以做的是在执行文件之前插入内容脚本,或者在插入文件后发送消息

What you can do is to either insert a content script before executing the file, or sending a message after inserting the file. I will show an example for these distinct methods below.

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

If you want to define some variables before inserting the file, just nest chrome.tabs.executeScript calls:

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

如果您的变量不那么简单,那么我建议您使用 JSON.stringify 将一个对象在一个字符串中:

If your variable is not as simple, then I recommend to use JSON.stringify to turn an object in a string:

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

With the previous method, the variables can be used in content.js in the following way:

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



执行JS文件后设置参数



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

Set parameters after execution of the JS file

The previous method can be used to set parameters after the JS file. Instead of defining variables directly in the global scope, you can use the message passing API to pass parameters:

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

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

In the content script (content.js), you can listen for these messages using the chrome.runtime.onMessage event, and handle the message:

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

这篇关于将参数传递给使用chrome.tabs.executeScript()注入的内容脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆