OiO.lk Blog javascript Able to read from google sheet but unable to write to google sheet using Javascript
javascript

Able to read from google sheet but unable to write to google sheet using Javascript


I’m able to read rows from my google sheet, but unable to write to it (append rows)..

That probably means that I’m clear on the whole authentication business right?

Below is my code for trying to write to the first two cells of my sheet. I don’t get any error message, I get a message that data has been successfully sent to the sheet, but I don’t see anything updated on my sheet

    const url = `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}/values/${sheetName}!A1:B1:append?valueInputOption=USER_ENTERED`; 
    chrome.identity.getAuthToken({ interactive: true }, function (token) {
      console.log(token);

      fetch(url, {
        method: "POST",
        range: "Sheet1!A1:B1",
        majorDimension: "ROWS",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          values: [[1, 2]],
        }),
      })
        .then((response) => response.json())
        .then((data) => sendResponse({ data }))
        .catch((error) => sendResponse({ error: error.message }));
    });

Below is my code for reading from the sheet. This works!

    const url = `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}/values/${sheetName}?key=${apiKey}`;
    chrome.identity.getAuthToken({ interactive: true }, function (token) {
      console.log(token);

     fetch(url)
        .then((response) => response.json())
        .then((data) => sendResponse({ data }))
        .catch((error) => sendResponse({ error: error.message }));
    });

In my manifest.json, I have as follows

 "oauth2": {
    "client_id": "<CLIENT ID>.apps.googleusercontent.com",
    "scopes": ["https://www.googleapis.com/auth/spreadsheets"]
  }

I get past the authorization/consent screen and any credential confirming steps, but I just don’t see anything updated on the actual sheet when I’m trying to write!

I tried changing the access level of the google sheet itself from Restricted to Anyone with link. For reading, setting the level to Anyone with link worked. For writing, neither of them worked.

I enabled viewing of protected range in the google sheet. Still nothing was written.



You need to sign in to view this answers

Exit mobile version