簡體   English   中英

我如何將不同變量的多個不同值從 popup.js 發送到 inject.js 以便可以在 inject.js 腳本中使用?

[英]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?

嗨,我不確定如何將 set 變量從 popup.js 發送到 inject.js。 假設我在 popup.js 中有這些變量:

// popup.js file
var year = "New Year"
var month = "New Month"
var day = "New Day"

現在我想發送每一個用於inject.js 腳本的每一個,但我不確定我會如何做到這一點。 有任何想法嗎?

// inject.js file
// some how import the values over from the popup.js
console.log(year + ", " + month +  ", " + day)

如果有人對如何做到這一點有任何想法,請幫助我非常堅持這一點,我是編碼的初學者,如果這是你以前見過的問題或重復的問題,我只是在尋求幫助,謝謝。

PS這是一個谷歌擴展,所以如果有任何想法可以與谷歌瀏覽器兼容,將不勝感激。

老派的做法是使用 window 並將您的變量分配給它的某些屬性。 如果這是一個小項目,而您只想完成它,這非常簡單。

在 popup.js 中,

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

現在在 inject.js

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

問題是您正在污染全局 scope。 如果另一個 javascript 文件(可能是第三方庫)使用 window.myVars 您可能會遇到問題。 這種方法更難調試,垃圾收集也可能受到影響。

一種非常現代的方法,但將使用本地存儲 API。

localStorage.setItem("year",year); // In popup.js
localStorage.getItem("yera"); // In inject.js

如果您可以使用最新的 es 模塊功能,那么您也可以這樣做,

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

然后在inject.js中,

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

console.log(getYear());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM