Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

javascript - adding custom functionality into chrome's console

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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"]
    }]
}

And your content script:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...