本文介绍了如何在“之前"从Chrome devtools扩展公开功能.页面加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个Chrome devtools扩展程序,该扩展程序将一个功能(extensionEntryPoint)暴露给被检查的页面.问题是extensionEntryPoint在被检查页面的初始脚本中不可用,并且无法运行.我可以从window.onload使用它,但是为时已晚.

I am working on a Chrome devtools extension that exposes a function (extensionEntryPoint) to the inspected page. The problem is that extensionEntryPoint is not available at the initial scripts in the inspected page loads and runs. I can use it from window.onload, but that is too late.

这是我的代码:

manifest.json:

{
  "name": "Extension",
  "version": "1",
  "manifest_version": 2,
  "permissions": [
    "activeTab"
  ],
  "web_accessible_resources": ["api.js"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-script.js"],
      "run_at": "document_start",
      "all_frames": true
    }
  ]
}

content-script.js:

const script = document.createElement("script");
script.src = chrome.extension.getURL("api.js");
document.documentElement.appendChild(script);

api.js:

function extensionEntryPoint(data) {
  console.log("Thanks for calling, I'll debug your data now!")
}

理想情况下,我希望页面加载时extensionEntryPoint可供页面上的任何脚本使用(例如,在DOMContentLoaded触发之前).这可能吗?

Ideally, I would want for extensionEntryPoint to be available to any script on the page as it's loading (e.g. before DOMContentLoaded fires). Is this possible?

推荐答案

由于 Chrome中的问题/错误当前,您的脚本在其他页面脚本中排队,因此不能保证它是第一个运行的脚本.

Due to a quirk/bug in Chrome currently your script is queued among other page scripts and hence it's not guaranteed to be the first one to run.

解决方案:将api.js的内容放入文字字符串中,并将其分配给script.textContent.
然后,您可以从manifest.json中删除web_accessible_resources.

Solution: put the contents of api.js inside a literal string and assign it to script.textContent.
And then you can remove web_accessible_resources from manifest.json.

content-script.js:

content-script.js:

const script = document.createElement("script");
script.textContent = `
// the actual contents of api.js
// .......
`;
document.documentElement.appendChild(script);
script.remove();

要在IDE中保留代码的语法高亮显示,请将代码放入函数中,但前提是它很小,因为浏览器将不得不执行两次额外的工作,即对该代码进行两次解析并对其进行字符串化.

To preserve syntax highlighting of the code in an IDE, put the code into a function, but only if it's small as the browser will have to do the extraneous work parsing that code twice and stringifying it.

script.textContent = '(' + (() => {
  // the actual contents of api.js
  // .......
}) + ')()';

如果您在运行代码之前(例如通过node.js)构建代码,则可以编写一个脚本,该脚本将api.js的内容嵌入,例如在内容脚本中的特殊注释占位符之后.

If you build your code prior to running it (e.g. via node.js), you can write a script that embeds the contents of api.js for example after a special comment placeholder inside your content script.

这篇关于如何在“之前"从Chrome devtools扩展公开功能.页面加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 01:36