简体   繁体   English

将变量从“浏览器操作”发送到“内容脚本”

[英]Send variables from “browser_action” to “content_scripts”

I am so new about making Chrome extension and somethings I will try : 我对制作Chrome扩展程序非常陌生,并且可以尝试以下操作:

I will to send JS variables from "browser_action" to "content_scripts" 我将JS变量从“ browser_action”发送到“ content_scripts”


"browser_action": {
    "default_popup": "src/browser_action/index.html"
},
"content_scripts": [
   {
      "matches": ["<all_urls>"],
      "js": ["src/inject/inject.js"]
   }
]

Example : If... 示例:如果...

src/browser_action/main.js : (browser_action) src / browser_action / main.js: (browser_action)

var MyVar = "Hello world";

And how to send MyVar to src/inject/inject.js ? 以及如何将MyVar发送到src / inject / inject.js Like.. 喜欢..

// What function I should do before to alert()?
if (typeof MyVar !== 'undefined') {
   alert(MyVar);
}

If you want to send message(or data) from background to content script, you can use chrome.tabs.sendMessage() . 如果要将消息(或数据)从后台发送到内容脚本,可以使用chrome.tabs.sendMessage() But you need to specify which tab(using tabId ) to send it to. 但是您需要指定要将其发送到哪个标签(使用tabId )。 You should read message passing in extensions . 您应该阅读扩展中传递的消息

Example : 范例:

Sending a message to the content script in the selected tab 将消息发送到所选选项卡中的内容脚本

main.js main.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});

On the receiving end, you need to set up an chrome.runtime.onMessage event listener to handle the message 在接收端,您需要设置chrome.runtime.onMessage事件监听器来处理消息

inject.js: inject.js:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

I did it with chrome.storage #ref 我用chrome.storage #ref做到了

Example : 范例:

Add "storage" permission on manifest.json manifest.json上添加“存储”权限

"permissions": [
   "storage"
]

On main.js (browser_action) 在main.js上 (browser_action)

chrome.storage.sync.set({'user':{email:'hello@world.com'}});

On inject.js (content_scripts) 在inject.js (content_scripts)

chrome.storage.onChanged.addListener(function(c,a){
   chrome.storage.sync.get('user',function(o){
      if(!$.isEmptyObject(o)){ // Check via jQuery function
          // Do somethings...
          console.log(o.user.email);
      }
   });
});

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

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