使用 ONLYOFFICE 宏生成和插入词义

2023年08月24日作者: Alina

要让写的内容更清楚,建议在文章中添加一些词义。使用 ONLYOFFICE 宏,这个可以来自动实现,无需浪费时间了。阅读本文,了解如何创建一个宏,从外部 API 中提取单词定义并将其无缝插入到文档中。

Generate and insert word definitions with ONLYOFFICE macro

访问 API

API Ninjas 是一个功能强大的 API 服务,提供各种免费 API,让开发者利用字典、语言翻译等功能增强应用程序。在本教程中,我们将使用提供单词定义的字典 API。开始前,您需要注册 API Ninjas 获取所需的 API 密钥。

构建宏

我们的宏应该获取所选单词的值,并从外部 API 获取其定义。然后,我们可以把词义插入到文档中。

首先,我们初始化必要的变量:

const oDocument = Api.GetDocument();
const oRange = oDocument.GetRangeBySelect();
const word = oRange.GetText();

在这里,oDocument 变量表示当前文档,oRange 变量表示选定的文本范围,word 变量表示选定单词的值。

接下来,我们使用 AJAX 向字典 API 提出请求。将 “your-api-key替换为您的实际 API 密钥:

    success: function(result) {
        console.log(result);
        const text = result.definition;
        // Continue to the next step...
    },
    error: function ajaxError(jqXHR) {
        console.error('Error: ', jqXHR.responseText);
    }
});

现在,我们向 API 端点发送一个 GET 请求,请求中包含所选单词和您的 API 密钥。在成功回调中,我们需要提取定义属性。

获取词义后,我们将其添加到文档中:

 success: function(result) {
        console.log(result);
    const text = result.definition; 
    const oParagraph = Api.CreateParagraph();
    oParagraph.AddText(text);
    oDocument.InsertContent([oParagraph], { "KeepTextOnly": true });
    }

在本节中,我们使用 Api.CreateParagraph() 创建新段落,使用 oParagraph.AddText(text) 添加获取的文本,最后使用 oDocument.InsertContent() 将内容插入到 oDocument 中。

整个宏代码如下:

(function()
{
const oDocument = Api.GetDocument();
const oRange = oDocument.GetRangeBySelect();
const word = oRange.GetText();
$.ajax({
    method: 'GET',
    url: 'https://api.api-ninjas.com/v1/dictionary?word=' + word,
    headers: { 'X-Api-Key': 'your-api-key'},
    contentType: 'application/json',
    success: function(result) {
        console.log(result);
    const text = result.definition; 
    const oParagraph = Api.CreateParagraph();
    oParagraph.AddText(text);
    oDocument.InsertContent([oParagraph], { "KeepTextOnly": true });
    },
    error: function ajaxError(jqXHR) {
        console.error('Error: ', jqXHR.responseText);
    }
});
})();

现在让我们运行宏,看看它是如何工作的!

希望该宏能够帮您简化文档流程,节省您的时间和精力。使用宏可以充分发挥 ONLYOFFICE 的潜力,提高工作效率。

我们邀请您深深了解 ONLYOFFICE API,并创建您自己的宏。 也欢迎您分享您的想法和建议,期待与您合作。祝探索之路好运!