在 Chrome 中通过用户脚本替换页面功能?
我创建了一个 Greasemonkey 脚本来替换页面函数:
(function() {
var oldFunc = func;
func = function() {
oldFunc();
// other stuff
};
)();
我一直想让这个脚本在 Gresemonkey 和 Chrome 中工作,并且了解到 Chrome 不支持 unsafeWindow
,因此一直在注入该脚本通过将函数转换为字符串并使用 setTimeout
进入页面:
setTimeout("(function(){var old=func;func=function(){old();/*other stuff*/}}())", 0);
这在 Greasemonkey 中工作得很好,但在 Chrome 中却什么也没有提供。它显然没有触发,但日志中也没有出现任何内容。我尝试过许多其他注射方式,但没有任何效果。 (为了测试,我还在函数顶部添加了一个 alert()
。)
setTimeout(..., 0)
— 无- 在作用域内运行函数,没有注入到页面中 - 没有警报,但控制台中“func未定义”
document.href = "javascript:..."
- 没有document.body.addEventListener("load" , ...)
— 无所有
这些都与 @run-at document-end
一起使用。
不幸的是,这是我的第一个 Chrome 用户脚本,即使经过一个小时左右的谷歌搜索和探索,我也不知道如何调试它。有什么帮助吗?
实际脚本,当前在 Greasemonkey 中运行: http://pastebin.com/HtLVjYHg
I've created a Greasemonkey script which replaces a page function:
(function() {
var oldFunc = func;
func = function() {
oldFunc();
// other stuff
};
)();
I had always intended this script to work in both Gresemonkey and Chrome and had read that Chrome doesn't support unsafeWindow
, so have been injecting the script into the page by converting the function to a string and using setTimeout
:
setTimeout("(function(){var old=func;func=function(){old();/*other stuff*/}}())", 0);
This works perfectly well in Greasemonkey, but gives me absolutely nothing in Chrome. It clearly isn't firing, but nothing appears in the log, either. I have tried a number of other injection styles, but can't get anything to work. (For testing, I also added an alert()
to the top of the function.)
setTimeout(..., 0)
— nothing- Running the function in-scope, without injection into the page — no alert, but "func is not defined" in console
document.href = "javascript:..."
— nothingdocument.body.addEventListener("load", ...)
— nothing
All of these are with @run-at document-end
.
Unfortunately, this being my first Chrome userscript, I'm at a loss as to how to debug it, even after an hour or so of Googling and poking around SO. Any help?
Actual script, currently working in Greasemonkey: http://pastebin.com/HtLVjYHg
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最后,我发现在 Chrome 中有效的唯一技术是使用 DOM 方法创建
节点。幸运的是,这似乎在 Firefox 和 Opera 中同样有效,并且通过
.toString()
变得相当轻松:最终脚本:http://userscripts.org/scripts/review/84394
In the end, the only technique I found which worked in Chrome was to create a
<script>
node using DOM methods. Fortunately, this seems to work equally well in Firefox and Opera and is made fairly painless by<func>.toString()
:Final script: http://userscripts.org/scripts/review/84394