简体   繁体   English

通过chrome扩展将变量传递到当前选项卡

[英]Pass variables to current tab via chrome extension

I am writing my first chrome extension, and I want to pass a variable to the currently opened tab and manipulate the DOM with it. 我正在编写我的第一个chrome扩展,我想将一个变量传递给当前打开的选项卡并使用它操作DOM。

My extension has a button, and when clicked, is executing this code: 我的扩展程序有一个按钮,单击时,正在执行此代码:

chrome.tabs.getSelected(null, function(tab) {
 chrome.tabs.executeScript(tab.id, {
  file: 'tabscript.js'
 });
});

This works fine, but I see no way to pass a variable to tabscript.js so it can be used on the opened tab. 这工作正常,但我认为无法将变量传递给tabscript.js,因此可以在打开的选项卡上使用它。

What do you need to pass a variable in to? 你需要将变量传递给什么? Do you have a function you are calling in your script? 你有在脚本中调用的函数吗?

It must be noted that you don't have access to the pages Javascript, just the DOM. 必须注意的是,您无法访问Javascript页面,只能访问DOM。

If you have a particular function that you have to call with specific parameters then you should investigate content scripts and message passing . 如果您具有必须使用特定参数调用的特定功能,则应调查内容脚本消息传递

Content scripts can get run on every page load (or a selection of pages), and you would use message passing to send a message from your extension button to the function in the content script. 内容脚本可以在每个页面加载(或选择的页面)上运行,您可以使用消息传递将消息从扩展按钮发送到内容脚本中的函数。

Alternativly, and closer to your original idea you can construct the function you want to call at run time using the following: 或者,更接近您最初的想法,您可以使用以下内容构建要在运行时调用的函数:

chrome.tabs.getSelected(null, function(tab) {
 chrome.tabs.executeScript(tab.id, {
  code: 'function(){ ...... your code built dynamically ......}'
 });
});

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

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