問題描述
是否可以在 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:
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);
因此,您將新函數指定為全局函數,以便您可以在 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
這篇關于在 chrome 的控制臺中添加自定義功能的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!