我正在尝试从Chrome扩展修改表格的insertRow函数。
oldInsRowFunc = document.getElementById(id).insertRow;
document.getElementById(id).insertRow = fakeInsertRow;
// .......
function fakeInsertRow (ind) {
alert("fakeInsertRow called");
}但是当它被调用时,调用的是本机函数,而不是fakeInsertRow。在其他情况下,如果我在javascript控制台中运行相同的代码,那么一切都很好。
发布于 2012-01-15 10:16:04
这不起作用的原因是因为由Chrome扩展添加的JavaScript (通常在内容脚本中)是在它自己的沙箱中执行的,该沙箱没有访问页面所在的JavaScript环境的权限。
以下是来自Chrome Extension的JavaScript的限制
Here are some examples of what content scripts can do:
* Find unlinked URLs in web pages and convert them into hyperlinks
* Increase the font size to make text more legible
* Find and process microformat data in the DOM
However, content scripts have some limitations. They cannot:
* Use chrome.* APIs (except for parts of chrome.extension)
* Use variables or functions defined by their extension's pages
* Use variables or functions defined by web pages or by other content scripts如果您的目标是真正包装/覆盖原生JavaScript/DOM访问方法(看起来很糟糕),那么在页面上下文中执行JavaScript的一种方法是创建一个外部托管的JavaScript文件,然后使用Chrome扩展向页面的DOM中添加一个引用外部托管文件的script元素。以这种方式插入的JavaScript将在pages JavaScript环境中运行(这意味着它不能用于Chrome扩展)。
Chrome扩展JavaScript应该是这样的:
document.body.appendChild(document.createElement("script")).src = "http://externally/hosted/javascript.js";那么位于http://externally/hosted/javascript.js的文件中的JavaScript代码可能就是上面的代码。
https://stackoverflow.com/questions/8773075
复制相似问题