Add conditional formatting rule

I believe that you will have to use a workaround in this case, if appropriate for your circumstance.

You would have to create a template sheet that had cells formatted by conditional formatting (manually done by you) in a source spreadsheet.

Then your script will copy this template sheet over to your target spreadsheet, and then use the copyTo method with advanced parameters of {formatOnly:true} to copy the format of one or a range of cells in the template sheet over to your chosen sheet (finally, you can delete this template sheet from the target spreadsheet). (The copyTo method only copies from one range to another within the same spreadsheet).

Something like this:

function transferFormatting() {
  var targetSs = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1dLv8V5fKmmxRLi5maLIOgrxVGVaqGGOD7STHbEremQs/edit#gid=0');
  var targetSsDisplaySheet = targetSs.getSheets()[0];
  var sourceSs = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/14RxLXktm0wj-lSFrl5Fas9B-smMYhknFt3-dYQbwH3o/edit#gid=933388275');
  var templateSheet = sourceSs.getSheetByName('Template');
  var targetSsFormatTemplateSheet =  templateSheet.copyTo(targetSs);

  targetSsFormatTemplateSheet.getRange("A1").copyTo(targetSsDisplaySheet.getRange("B:D"), {formatOnly:true});
  targetSs.deleteSheet(targetSsFormatTemplateSheet);
}

Also available is the Advanced Sheets Services to add Conditional Formatting from Google Apps Script.

Be sure to Enable Advanced Google Services from your script. Then you can use Sheets.Spreadsheets.batchUpdate(resource, spreadsheetId) to add conditional formatting using Google Sheets API v4 and Advanced Sheets Services

Navigate through each JSON representation object to piece together the full request:

  • AddConditionalFormatRuleRequest
    • ConditionalFormatRule
      • GridRange
      • BooleanRule
        • BooleanCondition
          • ConditionType
        • CellFormat
// Conditionally sets the background of cells to red within range B2:J1000
function setConditionalFormat() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sheet = ss.getSheets()[0]

  var format_req = {
    "requests": [{
      "addConditionalFormatRule": { 
        "rule": {
          "ranges": [{
            "sheetId": sheet.getSheetId(),
            "startRowIndex": 1,
            "endRowIndex": sheet.getMaxRows(),
            "startColumnIndex": 1,
            "endColumnIndex": 10
            }],
          "booleanRule": {
            "condition": {
              "type": "BLANK"
            },
            "format": {
              "backgroundColor": {
                "red": 1,
                "green": 0,
                "blue": 0,
                "alpha": 1
              }
            }
          }
        },
        "index": 0,
      }
    }],
  "includeSpreadsheetInResponse": false,
  }

  Sheets.Spreadsheets.batchUpdate(JSON.stringify(format_req), ss.getId())
}