这里我有 2 个 JavaScript 文件,我修改了 manifest.json
以避免错误:
{
"matches": [
"*://example.com"
],
"all_frames": true,
"css":[
"css/d.css",
"css/bootstrap.min.css"
],
"js": [
"scripts/jquery.min.js",
"scripts/home/msg.js",
"scripts/home/modify.js"
]
}
现在我有一个对象驻留在 msg.js
文件中,并且我只包含相关部分:
o = {
"timeStamps" : t.slice(),
"messages" : Object.assign({}, a)
}
console.log(o);
help(o.messages, o.timeStamps.length);
function help_final(){
return o;
}
这里 console.log(o)
工作正常。所以我希望这个对象 o
位于另一个名为 modified.js
的文件中。
这是我的modified.js
文件:
message_object = help_final();
$.getScript( "msg.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
//here i need to access the object o and store it as global variable
})
.fail(function( jqxhr, settings, exception ) {
});
$(document).ready(function() {
console.log("ready!");
//I need to access the obj here
console.log(message_object);
});
最佳答案
您应该导出该函数,以便您可以在浏览器中访问该特定文件之外的对象,以便您的所有文件都可以访问该对象(从看起来您试图将其存储到全局来看)。
所以在 msg.js 中只需在底部执行(假设这仅在浏览器中使用)
window.message_object = help_final;
然后只需在其他文件中稍微修改一下代码即可调用 message_object()
来获取 o
对象。
您还应该考虑使用 javascript 原型(prototype) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
关于javascript - 如何通过chrome扩展中的javascript文件访问驻留在另一个javascript文件中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38189487/