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 文件:

ma​​nifest.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/41243057/

相关文章:

javascript - 太多的重新渲染。 React 限制渲染次数以防止无限循环。接下来js错误

javascript - 如何使 Chrome 输入不可选择(但允许编辑)?

node.js - 打开 chrome-devtools ://URL from script/command line, 不是通过复制粘贴

javascript - 阻止 Chrome 在我的网站上自动建议信用卡号码

javascript - Chrome 控制台显示 "Navigated to http://localhost...."

javascript - 如何检测用户是否启用了 Mac OS 高对比度辅助功能设置?

javascript - 本地主机 : Image from origin 'null' has been blocked from loading by Cross-Origin Resource Sharing policy

.net - 是否可以从.net更改控制台窗口的图标?

ruby-on-rails - Rails控制台运行时无提示

javascript - ajax jquery 发布示例错误 503