简体   繁体   English

谷歌浏览器扩展 :: console.log() 来自后台页面?

[英]google chrome extension :: console.log() from background page?

If I call console.log('something');如果我调用console.log('something'); from the popup page, or any script included off that it works fine.从弹出页面或任何包含它的脚本中可以正常工作。

However as the background page is not directly run off the popup page it is not included in the console.但是,由于后台页面不是直接运行在弹出页面之外,因此它不包含在控制台中。

Is there a way that I can get console.log() 's in the background page to show up in the console for the popup page?有没有办法让我在后台页面中获取console.log()以显示在弹出页面的控制台中?

is there any way to, from the background page call a function in the popup page?有什么办法可以从后台页面调用弹出页面中的函数吗?

You can open the background page's console if you click on the "background.html" link in the extensions list.如果单击扩展列表中的“background.html”链接,则可以打开后台页面的控制台。

To access the background page that corresponds to your extensions open Settings / Extensions or open a new tab and enter chrome://extensions .要访问与您的扩展程序相对应的后台页面,请打开Settings / Extensions或打开一个新选项卡并输入chrome://extensions You will see something like this screenshot.您将看到类似此屏幕截图的内容。

Chrome 扩展程序对话框

Under your extension click on the link background page .在您的扩展程序下单击链接background page This opens a new window.这会打开一个新窗口。 For the context menu sample the window has the title: _generated_background_page.html .对于上下文菜单示例,窗口的标题为: _generated_background_page.html

Any extension page (except content scripts ) has direct access to the background page via chrome.extension.getBackgroundPage() .任何扩展页面(除了内容脚本)都可以通过chrome.extension.getBackgroundPage()直接访问后台页面。

That means, within the popup page , you can just do:这意味着,在弹出页面中,您可以执行以下操作:

chrome.extension.getBackgroundPage().console.log('foo');

To make it easier to use:为了更容易使用:

var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');

Now if you want to do the same within content scripts you have to use Message Passing to achieve that.现在如果你想在内容脚本中做同样的事情,你必须使用消息传递来实现这一点。 The reason, they both belong to different domains, which make sense.究其原因,它们都属于不同的领域,这是有道理的。 There are many examples in the Message Passing page for you to check out.消息传递页面中有许多示例供您查看。

Hope that clears everything.希望能清除一切。

To answer your question directly, when you call console.log("something") from the background, this message is logged, to the background page's console.要直接回答您的问题,当您从后台调用console.log("something") ,此消息会被记录到后台页面的控制台。 To view it, you may go to chrome://extensions/ and click on that inspect view under your extension.要查看它,您可以转到chrome://extensions/并单击您的扩展程序下的inspect view

When you click the popup, it's loaded into the current page, thus the console.log should show log message in the current page.当您单击弹出窗口时,它会加载到当前页面中,因此 console.log 应在当前页面中显示日志消息。

You can still use console.log(), but it gets logged into a separate console.您仍然可以使用 console.log(),但它会登录到单独的控制台。 In order to view it - right click on the extension icon and select "Inspect popup".为了查看它 - 右键单击​​扩展图标并选择“检查弹出窗口”。

The simplest solution would be to add the following code on the top of the file.最简单的解决方案是在文件顶部添加以下代码。 And than you can use all full Chrome console api as you would normally.而且您可以像往常一样使用所有完整的Chrome 控制台 API

 console = chrome.extension.getBackgroundPage().console;
// for instance, console.assert(1!=1) will return assertion error
// console.log("msg") ==> prints msg
// etc
const log = chrome.extension.getBackgroundPage().console.log;
log('something')

Open log:打开日志:

  • Open: chrome://extensions/打开:chrome://extensions/
  • Details > Background page详情 > 背景页面

Try this, if you want to log to the active page's console:试试这个,如果你想登录到活动页面的控制台:

chrome.tabs.executeScript({
    code: 'console.log("addd")'
});

In relation to the original question I'd like to add to the accepted answer by Mohamed Mansour that there is also a way to make this work the other way around:关于最初的问题,我想在 Mohamed Mansour 接受的答案中补充一点,还有一种方法可以使这项工作反过来:

You can access other extension pages (ie options page, popup page) from within the background page/script with the chrome.extension.getViews() call.您可以使用chrome.extension.getViews()调用从后台页面/脚本中访问其他扩展页面(即选项页面、弹出页面)。 As described here .如上所述这里

 // overwrite the console object with the right one.
var optionsPage = (  chrome.extension.getViews()  
                 &&  (chrome.extension.getViews().length > 1)  ) 
                ? chrome.extension.getViews()[1] : null;

 // safety precaution.
if (optionsPage) {
  var console = optionsPage.console;
}

It's an old post, with already good answers, but I add my two bits.这是一篇旧帖子,已经有了很好的答案,但我添加了两点。 I don't like to use console.log, I'd rather use a logger that logs to the console, or wherever I want, so I have a module defining a log function a bit like this one我不喜欢使用console.log,我宁愿使用记录到控制台或任何我想要的地方的记录器,所以我有一个模块定义了一个有点像这样的日志功能

function log(...args) {
  console.log(...args);
  chrome.extension.getBackgroundPage().console.log(...args);
}

When I call log("this is my log") it will write the message both in the popup console and the background console.当我调用 log("this is my log") 时,它将在弹出控制台和后台控制台中写入消息。

The advantage is to be able to change the behaviour of the logs without having to change the code (like disabling logs for production, etc...)优点是无需更改代码即可更改日志的行为(例如禁用生产日志等...)

To get a console log from a background page you need to write the following code snippet in your background page background.js -要从后台页面获取控制台日志,您需要在后台页面 background.js 中编写以下代码片段 -

 chrome.extension.getBackgroundPage().console.log('hello');

Then load the extension and inspect its background page to see the console log.然后加载扩展并检查其背景页面以查看控制台日志。

Go ahead!!加油!!

To view console while debugging your chrome extension, you should use the chrome.extension.getBackgroundPage();要在调试 chrome 扩展时查看控制台,您应该使用chrome.extension.getBackgroundPage(); API, after that you can use console.log() as usual: API,之后你可以像往常一样使用console.log()

chrome.extension.getBackgroundPage().console.log('Testing');

This is good when you use multiple time, so for that you create custom function:当您多次使用时,这很好,因此您可以创建自定义函数:

  const console = {
    log: (info) => chrome.extension.getBackgroundPage().console.log(info),
  };
  console.log("foo");

you only use console.log('learnin') everywhere你只在任何地方使用console.log('learnin')

目前使用 Manifest 3 和 Service Worker,您只需要转到Extensions Page / Details并单击Inspect Views / Service Worker

chrome.extension.getBackgroundPage() I get null chrome.extension.getBackgroundPage()我得到null

and accrouding documentation ,和积累文件

Background pages are replaced by service workers in MV3.后台页面被 MV3 中的 Service Worker 替换。

  • Replace background.page or background.scripts with background.service_worker in manifest.json.更换background.pagebackground.scriptsbackground.service_worker manifest.json中。 Note that the service_worker field takes a string, not an array of strings.请注意, service_worker 字段采用字符串,而不是字符串数组。

manifest.json清单文件

{
  "manifest_version": 3,
  "name": "",
  "version": "",
  "background": {
    "service_worker": "background.js"
  }
}

anyway, I don't know how to use getBackgroundPage , but I found another solution as below,无论如何,我不知道如何使用getBackgroundPage ,但我找到了另一个解决方案,如下所示,

Solution解决方案

use the chrome.scripting.executeScript使用chrome.scripting.executeScript

So you can inject any script or file.所以你可以注入任何脚本或文件。 You can directly click inspect (F12) and can debug the function.可以直接点击inspect(F12),可以调试该功能。

for example例如

chrome.commands.onCommand.addListener((cmdName) => {
    switch (cmdName) {
      case "show-alert":
        chrome.storage.sync.set({msg: cmdName}) // You can not get the context on the function, so using the Storage API to help you. // https://developer.chrome.com/docs/extensions/reference/storage/
        chrome.tabs.query({active: true, currentWindow: true}).then(([tab])=>{
          chrome.scripting.executeScript({
            target: {tabId: tab.id},
            function: () => {
              chrome.storage.sync.get(['msg'], ({msg})=> {
                console.log(`${msg}`)
                alert(`Command: ${msg}`)
              })
            }
          })
        })
        break
      default:
        alert(`Unknown Command: ${cmdName}`)
    }
  })

I create an open-source for you reference.我创建了一个开源供您参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM