· 4 years ago · May 18, 2021, 04:54 PM
1/**
2* Returns the last 6 month's estimated traffic values for a domain.
3*
4* @param {"https://www.shopify.com"} url input the domain.
5* @return last 6 months estimated traffic values.
6* @customfunction
7*/
8
9
10function getCompetitorTraffic(url) {
11
12 // add API key from https://rapidapi.com/apifactory/api/similarweb2
13 var apiKey = '5ba70d07d4msh1141d19c5cb0bdcp16cb7djsnc4c20a5dcf1c';
14 var url = encodeURIComponent(url);
15
16 var options = {
17 'method': 'GET',
18 'muteHttpExceptions': true,
19 'headers': {
20 'x-rapidapi-key': apiKey,
21 'x-rapidapi-host': 'similarweb2.p.rapidapi.com'
22 }
23 };
24 // perform GET request to API
25 var response = UrlFetchApp.fetch("https://similarweb2.p.rapidapi.com/trafficoverview?website="+url, options);
26
27 // check response and return error if website is not available
28 try {
29
30 if(response.getResponseCode() === 200) {
31
32 // monthly visits data and organic search %
33 var json = response.getContentText();
34 var results = JSON.parse(json).monthlyVisitsEstimate;
35 var organic = JSON.parse(json).trafficSources.Search;
36
37 var traffic = Object.entries(results);
38
39 // multiply each traffic value by organic search %
40 traffic.forEach((row,x) => {
41 traffic[x][1] *= organic;
42 });
43
44 // add column headers
45 traffic.unshift(["Date","Organic Traffic"]);
46
47 return traffic;
48
49 }
50
51 } catch (err) {
52
53 return 'No website data';
54 }
55}
56
57