[英]How would I send multiple different values of different variables from popup.js to inject.js so those can be used in the inject.js script?
Hi I am unsure on how would I send set variables from popup.js to inject.js.嗨,我不确定如何将 set 变量从 popup.js 发送到 inject.js。 Lets say I've got these variables in popup.js:假设我在 popup.js 中有这些变量:
// popup.js file
var year = "New Year"
var month = "New Month"
var day = "New Day"
Now I would like to send each an every single one to be used in inject.js script and I am unsure how I would do that.现在我想发送每一个用于inject.js 脚本的每一个,但我不确定我会如何做到这一点。 Any ideas?有任何想法吗?
// inject.js file
// some how import the values over from the popup.js
console.log(year + ", " + month + ", " + day)
If anyone has any idea on how to do this please help I'am very stuck on this and I am beginner in coding so sorry if this is a question that you have seen before or its repetitive I just am looking for help thank you.如果有人对如何做到这一点有任何想法,请帮助我非常坚持这一点,我是编码的初学者,如果这是你以前见过的问题或重复的问题,我只是在寻求帮助,谢谢。
PS This is for a google extension so if any ideas could be compatible with google chrome would be grateful. PS这是一个谷歌扩展,所以如果有任何想法可以与谷歌浏览器兼容,将不胜感激。
The old school way of doing it is to use the window and assign your variable to some properties of it.老派的做法是使用 window 并将您的变量分配给它的某些属性。 If this is a small project and you just want to get it done this is very simple.如果这是一个小项目,而您只想完成它,这非常简单。
In popup.js do,在 popup.js 中,
window.myVars = {
"year": year,
"month": month,
"day": day
};
Now on inject.js现在在 inject.js
console.log(window.myVars.year + ", " + window.myVars.month + ", " + window.myVars.day)
The problem with this is you are polluting the global scope.问题是您正在污染全局 scope。 If another javascript file ( maybe a third party library ) uses window.myVars you could run into a problem.如果另一个 javascript 文件(可能是第三方库)使用 window.myVars 您可能会遇到问题。 This approach is much harder to debug and garbage collection may also be affected.这种方法更难调试,垃圾收集也可能受到影响。
A much modern approach but would be to use the local storage API.一种非常现代的方法,但将使用本地存储 API。
localStorage.setItem("year",year); // In popup.js
localStorage.getItem("yera"); // In inject.js
If you can use the latest es module feature then you could also do,如果您可以使用最新的 es 模块功能,那么您也可以这样做,
export const getYear = (() => year ); // In popup.js
export const getMonth = (() => month );
export const getDay = (() => day );
then in inject.js,然后在inject.js中,
import getYear,getMonth,getDay from ./popup.js
console.log(getYear());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.