简体   繁体   中英

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. Lets say I've got these variables in 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. 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.

The old school way of doing it is to use the window and assign your variable to some properties of it. If this is a small project and you just want to get it done this is very simple.

In popup.js do,

window.myVars = {
                    "year": year,
                    "month": month,
                    "day": day
                };

Now on inject.js

console.log(window.myVars.year + ", " + window.myVars.month +  ", " + window.myVars.day)

The problem with this is you are polluting the global scope. If another javascript file ( maybe a third party library ) uses window.myVars you could run into a problem. 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.

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,

export const getYear = (() => year ); // In popup.js
export const getMonth = (() => month );
export const getDay = (() => day );

then in inject.js,

import getYear,getMonth,getDay from ./popup.js

console.log(getYear());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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