在Chrome的控制台中添加自定义功能 [英] adding custom functionality into chrome's console

查看:732
本文介绍了在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.

推荐答案

。您需要的是创建内容脚本。此脚本将注入任何页面,并创建一些必要的全局函数,您将在控制台中使用。最具挑战性的部分是如何使这些自定义内容scrtipt函数成为您的实际窗口对象的一部分,因为通常您不能访问在您的内容中定义的函数或变量脚本从其余的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

另请参阅这个

So you specify your new functions as global functions so that you could use them in console.
Also take a look at this post

这篇关于在Chrome的控制台中添加自定义功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆