Bookmarklet to save URL in Google Spreadsheet

2019-05-10 04:10发布

问题:

I want to create a simple bookmarklet, that grabs the URL of the current webpage "location.ref" and saves it in a Google Spreadsheet. After it saves it, I want to stay on the current webpage.

The only way I know of writing to Google Spreadsheet is using Google App Script. So I wrote a simple script that does just that:

function doGet(request) {
  var ss = SpreadsheetApp.openByUrl( "https://docs.google.com/spreadsheet/ccc?key=<MY-SPREADSHEET-ID>");

 var sheet = ss.getSheets()[0];
 var headers = ["Timestamp", "url"];

 var nextRow = sheet.getLastRow(); 
 var cell = sheet.getRange('a1');
 var col = 0;
 for (i in headers){
    if (headers[i] == "Timestamp"){
       val = new Date();
    } else {
       val = request.parameter[headers[i]]; 
    }
    cell.offset(nextRow, col).setValue(val);
    col++;
 }



   return ContentService.createTextOutput(request.parameter.url)
   .setMimeType(ContentService.MimeType.TEXT);
}

I published this as a webapp. I wrote the bookmarklet:

<a href="javascript:(

   function(){ 
     alert(window.open('https://script.google.com/macros/s/<MYWEBAPP>/exec?url='+encodeURIComponent(location.href), '_self')); 

   }

  )();"> 

BOOKMARK

</a>

So far so good. It actually works when I click on the bookmarklet, it does grab the URL of the current webpage and save it in my spreadsheet. But then, the webapp returns a text response and the bookmarklet displays the text causing me to move away from my current website.

Is there a way to ignore the response? GAS webapp script requires me to use doGet() that has to return something. Is there a way to not return anything from GAS script? Alternatively, is there a way i could use some other call to replace window.open to invoke the webapp that would allow me to store the response in a variable and ignore it?

回答1:

Instead of using window.open you may consider sending a HTTP GET request using XMLHttpRequest.

Refer here on its usage.



回答2:

Change _self to something else, e.g. bookmarker and it will open in a new window or tab. If you use it on many pages, they will all reuse the same tab if it keeps the same name.