通过 chrome 扩展访问控制台日志命令

Oli*_*ski 2 javascript console dom google-chrome google-chrome-extension

我希望通过 Chrome 扩展覆盖现有的控制台命令 - 原因是我希望记录特定站点的控制台日志。

不幸的是我似乎无法更新 DOM,这是我到目前为止所尝试的:

// Run functions on page change
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
    var s = document.createElement('script');
    // TODO: add "script.js" to web_accessible_resources in manifest.json
    s.src = chrome.runtime.getURL('core/js/app/console.js');
    s.onload = function() {
        this.remove();
    };
    (document.head || document.documentElement).appendChild(s);
});
Run Code Online (Sandbox Code Playgroud)

控制台.js

// Replace functionality of console log
console.defaultLog = console.log.bind(console);
console.logs = [];
console.log = function(){
    console.defaultLog.apply(console, arguments);
    console.logs.push(Array.from(arguments));
};

// Replace functionality of console error
console.defaultError = console.error.bind(console);
console.errors = [];
console.error = function(){
    console.defaultError.apply(console, arguments);
    console.errors.push(Array.from(arguments));
};

// Replace functionality of console warn
console.defaultWarn = console.warn.bind(console);
console.warns = [];
console.warn = function(){
    console.defaultWarn.apply(console, arguments);
    console.warns.push(Array.from(arguments));
};

// Replace functionality of console debug
console.defaultDebug = console.debug.bind(console);
console.debugs = [];
console.debug = function(){
    console.defaultDebug.apply(console, arguments);
    console.debugs.push(Array.from(arguments));
};
Run Code Online (Sandbox Code Playgroud)

该脚本成功运行并发出警报()。

我的目标是访问 console.logs - 但它是未定义的,这意味着我无法访问 DOM,尽管注入了脚本。

如果不可能,甚至第三方集成也会有帮助,即 Java 或 C?

任何想法将不胜感激:)

Chc*_*oam 5

我发现这篇文章,我认为 Tampermonkey 注入了一个带有您在 Tampermonkey Chrome 扩展页面中添加的即时函数的脚本,我在 Wappalyzer 等扩展中发现了类似的东西,并且看起来不错且安全,您可以使用WebRequest注入您的网站正如帖子所说,在页面完全加载之前新的“polyfill”。

这里是我之前提到的Wappalyzer的例子,这是使用代码注入在StackOverflow中使用Wappalyzer加载JS,我还没有用Tampermonkey测试它

在此输入图像描述

编辑

检查Wappalyzer,如何注入代码是简单的部分,您可以使用(Wappalyzer github示例):

const script = document.createElement('script')
script.setAttribute('src', chrome.extension.getURL('js/inject.js'))
Run Code Online (Sandbox Code Playgroud)

这可能无法解决您的问题,此代码在所有内容加载到 DOM 后执行。但是,您可以在这篇文章中找到如何解决该问题

我建议使用 onCommited 事件(doc1 / doc2

使用 mozilla.org 示例,您将得到类似的内容

 const filter = {
  url: //website to track logs
  [
    {hostContains: "example.com"},
    {hostPrefix: "developer"}
  ]
}

function logOnCommitted(details) {
  //Inject Script on webpage
}

browser.webNavigation.onCommitted.addListener(logOnCommitted, filter);
Run Code Online (Sandbox Code Playgroud)