问题
How to find if a google document is blank using App script? I tried this
function myFunction()
{
var body = DocumentApp.getActiveDocument().getBody();
var para = body.getParagraphs();
var count = 0;
for (i = 0; i < para.length; i++)
{
if (para[i].getText() != "")
count++;
}
if(count=0)
Logger.log("Empty");
else
Logger.log("NOT EMPTY")
}
I am sure that this works good only if the document has text content alone. I am eager to know if there is any way to find if the document is blank.
回答1:
A document always has at least one paragraph element, so you can't really rely on a zero-count return. You could check the length of the elements in the body and then trigger some more tests for a true check for blankness.
function blankDoc() {
var body = DocumentApp.getActiveDocument().getBody();
// Find the number of children in the body
Logger.log(body.getNumChildren());
for(var i = 0; i<body.getNumChildren();i++) {
Logger.log(body.getChild(i).getType());
// Test for text in the paragraph
if(body.getChild(i).getType() == DocumentApp.ElementType.PARAGRAPH) {
// get the text, check for a 0 length
var para = body.getChild(i).asParagraph().getText();
Logger.log(para.length);
// use another if block to do something...
}
}
// check for images
var imgs = body.getImages();
if(imgs.length > 0) {
Logger.log("There's an image");
}
}
It's not perfect, but it gets you closer. Go through the documentation on what elements to check for in the Body
of the doc and just add from there.
来源:https://stackoverflow.com/questions/43999152/find-if-a-google-document-is-blank-using-google-script