在 chrome 的控制台中添加自定义功能
是否可以在 google-chrome 中拥有始终在控制台中可用的自定义功能(无论加载什么页面)?例如,我想要一个名为 echo 的函数,它只是 console.log 的一个包装器.这只是节省了一些输入,但稍后我可能想创建一些有用的调试功能.
Is it possible to have custom functions in google-chrome that will be always available in console (no matter what page is loaded)? For instance, I would like to have a function called echo that would be just a wrapper around console.log. This just saves a bit of typing but later I might want to create some useful debug functionality.
推荐答案
这很容易实现.您需要创建一个内容脚本.该脚本将被注入任何页面并创建一些您将在控制台中使用的必要全局函数.最具挑战性的部分是如何使这些自定义内容脚本函数成为您实际 window
对象的一部分,因为通常您无法从其余部分访问您在内容脚本中定义的函数或变量不在内容脚本中的 javascript 代码.内容脚本在所谓的隔离环境中运行.
Well it's pretty easy to accomplish. What you need is to create a content script. This script would be injected in any page and create some necessary global functions you would use in your console. The most challenging part is how to make those custom content scrtipt functions to be part of your actual window
object, because normally you can't access functions or variables you define in your content script from the rest of the javascript code which is not within content script. Content scripts run in so-called isolated enviroment.
内容脚本在称为孤立世界的特殊环境中执行.他们可以访问被注入页面的 DOM,但不能访问页面创建的任何 JavaScript 变量或函数.它查看每个内容脚本,就好像它正在运行的页面上没有执行其他 JavaScript.反过来也是如此:页面上运行的 JavaScript 不能调用任何函数或访问任何由内容脚本定义的变量.
Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.
但是有一些奇特的解决方法.
你定义你的清单文件如下:
But there are fancy workaround.
You define your manifest file as follows:
manifest.json
{
"name": "Content script",
"version": "0.1",
"manifest_version": 2,
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["console.js"]
}]
}
还有你的内容脚本:
console.js
function customConsole() {
window.myNewFunction = function() {
console.log("Hello I'm available from console.");
};
}
var script = document.createElement('script'),
code = document.createTextNode('(' + customConsole + ')();');
script.appendChild(code);
(document.body || document.head || document.documentElement).appendChild(script);
因此,您将新函数指定为全局函数,以便您可以在 console
中使用它们.
也看看这个 post
So you specify your new functions as global functions so that you could use them in console
.
Also take a look at this post
相关文章