Tạo một App Script mới theo hướng dẫn trong bài viêt Tạo ứng dụng Google App Script từ Google Docs.
Trong Google Apps Script, hàm onOpen()
là một hàm đặc biệt (special trigger) được tự động gọi khi tài liệu (Google Docs, Sheets, Slides, hoặc Forms) được mở. Điều này rất hữu ích vì khi giúp chúng ta không cần phải vào script để chạy thủ công. Hàm thường được sử dụng để thực hiện các tác vụ khởi tạo, chẳng hạn như:
Tạo menu mỗi khi mở Google Docs như sau:
function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('Công cụ Tự động')
.addItem('Chèn Tiêu đề & Nội dung', 'insertFormattedText')
.addToUi();
}
Bây giờ sẽ viết chức năng cho hàm insertFormattedText
:
function insertFormattedText() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var cursor = doc.getCursor();
if (cursor) {
var header = body.insertParagraph(body.getChildIndex(cursor.getElement()), "Tiêu đề Mẫu");
header.setHeading(DocumentApp.ParagraphHeading.HEADING1);
header.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
var content = body.insertParagraph(body.getChildIndex(header) + 1,
"Đây là một đoạn nội dung mẫu được chèn tự động bằng Google Apps Script. " +
"Bạn có thể tùy chỉnh nội dung này theo ý muốn!");
content.setAlignment(DocumentApp.HorizontalAlignment.JUSTIFY);
content.setFontSize(12);
content.setFontFamily("Arial");
} else {
DocumentApp.getUi().alert("Vui lòng đặt con trỏ vào vị trí cần chèn!");
}
}
Quay lại file Google Doc để kiểm tra kết quả:
Xem mã nguồn trong phần Tiện ích -> App Script
của file Google Docs https://docs.google.com/document/d/1I894aTTHqAwZfFqIZUilTOgBdx7tWrswiCtB8dCZYwU/edit?usp=sharing, file menu_new.gs
.