javascript - 将自定义功能添加到 chrome 的控制台

标签 javascript google-chrome console customization

是否可以在 google-chrome 中拥有自定义功能,这些功能将始终在控制台中可用(无论加载什么页面)?例如,我想要一个名为 echo 的函数,它只是 console.log 的包装器。这只是节省了一些输入,但稍后我可能想创建一些有用的调试功能。

最佳答案

好吧,这很容易实现。你需要的是创建一个 content script .该脚本将被注入(inject)任何页面并创建一些您将在控制台中使用的必要全局函数。最具挑战性的部分是如何使这些自定义内容脚本函数成为您实际 window 对象的一部分,因为通常您无法从其余部分访问您在内容脚本中定义的函数或变量不在内容脚本中的 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.

但也有一些奇特的解决方法。
您定义您的 list 文件如下:

list .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);

因此您将新函数指定为全局函数,以便您可以在控制台中使用它们。
也看看这个 post

关于javascript - 将自定义功能添加到 chrome 的控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9051205/

相关文章:

javascript - 如何在javascript for循环中打印大括号

javascript - 从 JS 应用的 CSS3 转换不起作用

javascript - FTScroller - 未将滚动固定到底部

google-chrome - Chrome - child 剪辑CSS3圆形边框?

python - 如何禁用标准错误流的日志记录?

javascript - 我可以制作一个从 B 而不是 A 开始的按字母顺序排列的列表吗

google-chrome - getUserMedia 在 Chrome 中导致 TrackStartError

html - div "style=resize:both"无法在 chrome 中缩小(但它在 firefox 中有效)

windows - Windows 不再有 SVN 控制台客户端?

c++ - 异步 Windows 控制台输入同时输出