将表格数据从我的Chrome扩展程序写入Google表格

时间:2018-11-09 14:22:24

标签: javascript google-chrome-extension google-sheets-api

已更新摘要和今天的进度

我正在编写一个Chrome扩展程序,该扩展程序本质上是带有表单的弹出窗口,并且我想将在表单中输入的数据写入Google表格。目前,我的扩展程序由manifest.json和一个弹出脚本以及一个后台脚本组成。

manifest.json(相关部分):

"background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_scripts": [{ "js": ["content.js"], "matches": ["<all_urls>"] }],
  "permissions": [
    "tabs",
    "storage",
    "<all_urls>",
    "identity",
    "https://*.googleapis.com/*"
  ]

popup.js(注意:这是跟踪MS症状的扩展)

const app = {

  symptoms: [],

  init: function () {
    //cache some element references
    let formEl = document.getElementById("symptoms-form");

    let fatigue = document.getElementById("fatigue");
    let tingling = document.getElementById("tingling");
    let weakness = document.getElementById("weakness");
    let vision = document.getElementById("vision");
    let dizzy = document.getElementById("dizzy");
    let cognition = document.getElementById("cognition");
    let depression = document.getElementById("depression");
    let balance = document.getElementById("balance");

    //upon submit, update symptoms obj and send to background
    formEl.addEventListener("submit", ev => {
      ev.preventDefault();
      console.log('button click')
      this.symptoms.push({fatigue: fatigue.value})
      this.symptoms.push({tingling: tingling.value})
      this.symptoms.push({weakness: weakness.value})
      this.symptoms.push({vision: vision.value})
      this.symptoms.push({dizzy: dizzy.value})
      this.symptoms.push({cognition: cognition.value})
      this.symptoms.push({depression: depression.value})
      this.symptoms.push({balance: balance.value})

      // chrome.runtime.sendMessage({fn: 'getSymptoms'}, function(response) {
      //   console.log('popup got response', response)
      // })

      chrome.runtime.sendMessage({fn: 'setSymptoms', symptoms: this.symptoms})
    });

  }
}

document.addEventListener('DOMContentLoaded', () => {
  app.init();
})

background.js-注意:我当前的解决方法是将数据加载到Firebase中,您将在下面看到:

console.log("Background running");

const background = {
  symptoms: [],

  init: function() {
    //listen for any messages and route them to functions
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.fn in background) {
        background[request.fn](request, sender, sendResponse);
      }
      const jsonObj = {}
      jsonObj['symptoms'] = request.symptoms
      console.log("message received", jsonObj);


      this.postSymptoms(jsonObj)
    });
  },

  postSymptoms: function(msg) {
    const xhr = new XMLHttpRequest();

    xhr.open("POST", "https://ms-mysymptoms-1541705437963.firebaseio.com/symptoms.json", true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.send(msg);
  }
};

background.init();

我已经在Google Developers控制台中设置了一个新项目,启用了Google Sheets API,并设置了我的凭据和API令牌。我在Google API资源管理器中测试了身份验证的设置正确,并且确实可以在表格中写一行。这是个好消息!

我现在无法直接从我的Chrome扩展程序中进行操作(写入数据)。到目前为止,我已经保存了所有凭据,设置了配置文件,并将append方法写入本地的单独文件中。

sheets.js:

const {authorize, google} = require('./config')
const fs = require('fs')

const spreadsheetId = '---removed for this post--'
const append = (range, values) => {
  fs.readFile('client_secret.json', (err, content) => {
    if (err) return console.log('Error loading client secret file:', err);
    // Authorize a client with credentials, then call the Google Sheets API.
    authorize(JSON.parse(content), (auth) => {
      const sheets = google.sheets({
        version: 'v4',
        auth
      });
      const valueInputOption = 'USER_ENTERED';
      const resource = {
        values
      };
      sheets.spreadsheets.values.append({
        spreadsheetId,
        range,
        valueInputOption,
        resource
      }, (err, result) => {
        if (err) {
          console.log(err);
        } else {
          console.log("Success!");
        }
      });
    });
  });
}

// module.exports = {
//     append
// };

但是,当我尝试将此代码集成到我的弹出脚本中时,遇到一个错误,因为为了引用该配置数据和那个append方法,我必须在弹出脚本中使用require。由于弹出脚本正在浏览器中运行,因此无法使用require(即没有webpack)。

我敢肯定我将解决所有这些错误,因此,如果我的配置和身份验证存储在我本地的文件中,那么我可以在正确的方向上使用推送方式来确定如何从浏览器进行身份验证和附加到表格电脑。

我考虑过的解决方案:

1-启动REST API,将表单中的数据发布到该端点,并使其充当Google Sheets API的代理-这不是理想选择。

2-使用webpack,以便我可以在弹出文件中使用require

推荐这样做的方法是什么?如何将身份验证和Google表格配合使用到此扩展程序中?

2 个答案:

答案 0 :(得分:1)

使用Google API写入电子表格是PUT,而不是POST。

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update

我使用chrome.identity.getAuthToken成功完成了此任务,然后使用以下命令运行抓取操作:

    chrome.identity.getAuthToken({interactive: true}, function(token) {
        var params = {
            'values': [
                ['Row 1 Col A','Row 1 Col B'],
                ['Row 2 Col A','Row 2 Col B'],
            ]
        };
        let init = {
            method: 'PUT',
            async: true,
            body: JSON.stringify(params),
            headers: {
                Authorization: 'Bearer ' + token,
                Content-Type': 'application/json'
            },
            contentType: 'json',
        };
        fetch('https://sheets.googleapis.com/v4/spreadsheets/***YOUR SHEET ID****/values/****YOUR RANGE*****?valueInputOption=USER_ENTERED&key=***YOUR API KEY***', init)
            .then((response) => response.json())
            .then(function(data) {
                //console.log(data);
                //Returns spreadsheet ID, update tange, cols and rows
            });
        })
   });

这些都在后台脚本中,我将第1行第A列等作为值,它将成为范围的第一个单元格。

希望有帮助。

答案 1 :(得分:0)

小心!如果要追加数据,则?查询参数位于:append之后。

fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${range}:append?valueInputOption=${valueInputOption}`, init)