GI-*_*O5T 4 javascript google-chrome google-docs google-docs-api google-chrome-extension
我编写了一个 Chrome 扩展程序,用于计算 Google 文档中的字数,并将它们与数据源(CSV、表格或数据库)中的建议字数进行比较。
我的方法是解析span.kix-lineview-text-block页面上的每个内容,当 Google切换到 SVG 画布显示时,该方法停止工作。这是显示所有字数为 0 的屏幕截图。
解析页面的推荐替代方法是身份验证。即使用 Oauth 2.0 通过记录良好的 Google Docs API来授权请求并编辑内容。
GDocs 的 API 概述很有意义。但我对身份验证很陌生,而且我太菜鸟了,无法理解这个答案。谷歌提供了一个快速入门教程,但我无法让它作为扩展运行。
显然我的知识存在差距,而且我不知道要搜索什么(“Google Docs chrome扩展身份验证”引导我来到这里......)大多数Google的示例都使用 Java/PHP/Python,这让我想知道如果我找错了树。
比我聪明的人可以指出我正在寻找什么和/或在哪里学习它吗?
TL;DR - 我有一个主要工作的 Chrome 扩展程序,需要来自 Google 文档的数据。如何画猫头鹰的其余部分?
当数据全部存在于本地时,从远程 API 获取数据似乎很浪费,因此这里有一个解决方法,可以从文档内部提取文本。由于内容脚本在隔离环境中运行,因此我们必须将提取器代码放入页面上下文中,并使用 DOM 消息传递与内容脚本进行通信。
内容脚本(ManifestV2):
// Adds the extractor into the page context (aka "main world")
const script = document.createElement('script');
const eventId = `${Math.random()}${performance.now()}`;
script.textContent = `(${eventId => {
window.addEventListener(eventId, () => {
const doc = document.querySelector('.docs-texteventtarget-iframe').contentDocument;
const key = Object.keys(doc).find(k => k.startsWith('closure_'));
const res = dig(key ? doc[key] : doc.defaultView, new Set());
window.dispatchEvent(new CustomEvent(`${eventId}res`, { detail: res || '' }));
});
function dig(src, seen) {
seen.add(src);
if (!Array.isArray(src)) src = Object.values(src);
for (let v, len = src.length, i = 0; i < len; i++) {
try {
if (!(v = src[i]) ||
Object.prototype.toString.call(v) === '[object Window]' ||
seen.has(v)) {
continue;
}
} catch (e) {}
seen.add(v)
if (typeof v === 'string' && v[0] === '\x03' && v.endsWith('\n') ||
typeof v === 'object' && (v = dig(v, seen))) {
return v;
}
}
}
}})(${JSON.stringify(eventId)})`;
document.documentElement.appendChild(script);
script.remove();
// Listens for messages from the extension
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === 'getDocText') {
sendResponse(getDocText());
}
});
// Calls the extractor via synchronous DOM messaging
function getDocText() {
let res;
window.addEventListener(`${eventId}res`, e => { res = e.detail }, {once: true});
window.dispatchEvent(new CustomEvent(eventId));
return res;
}
Run Code Online (Sandbox Code Playgroud)
在 ManifestV3 中,唯一的区别是您将使用 script.src + web_accessible_resources 中公开的单独脚本文件代替 script.textContent,如此处方法 1 所示。未来ManifestV3将允许直接在主世界中注册代码。
| 归档时间: |
|
| 查看次数: |
1403 次 |
| 最近记录: |