是否可以添加我的自定义JS文件,以便页面DOM可以访问它?

时间:2011-05-23 20:17:57

标签: google-chrome-extension

现在的问题是,如果我添加一些DOM元素,我必须将所有JS放在标签中,这会在代码中造成巨大的混乱,例如:

<div onclick='//js monstrous oneliner with function declarations and so on..
              //that must be repeated many times multipcating the whole mess..
  '>
 Here some pure html thing.
</div>

那么我可以将自定义JS文件添加到渲染文档中,就像我能够添加DOM元素一样吗?

2 个答案:

答案 0 :(得分:3)

您可以将扩展程序中的JavaScript文件注入页面。然后,onclick处理程序可以直接引用它。

假设您的扩展程序中有一个脚本:

// myfile.js
function hello() {
  alert('hello world');
}

在内容脚本中,创建脚本标记:

var script = document.createElement('script');
script.src = chrome.extension.getURL('/myfile.js');

现在,您可以像这样编写HTML:

<div onclick="hello">…</div>

请注意,由于内容脚本不在与页面相同的JavaScript上下文中运行,因此不会在您的内容扩展程序中运行。

var div = document.createElement('div');
div.onclick = someFuncInMyExtension;

答案 1 :(得分:0)

是的,这很简单:看到这个文件只是为了有一个想法http://blog.jeffhaynie.us/cross-browser-way-to-dynamically-load-javascript.html