1

Hi actually I am trying to build a chrome extension for bulk tagging functionality by using gmail api. As there is no chance to build a button UI with gmail api I am using inboxsdk for button creation in gmail inbox and for bulk tagging functionality to work on button click I am using gmail api. In the sense when the button is clicked the selected mails should get tagged with the "general" label in gmail inbox. The button which I am using will be displayed in the gmail toolbar next to delete button in existing gmail scenario.

Now where I am facing the issue is that When I am debugging the code I am not finding any errors but when I am trying to execute the code. The mail is automatically redirected to gmail login page and this login page is only getting repeated every time.

enter image description here

Now I am posting the code below

manifest.json:

{
  "name": "Gmail Extension",
  "description": "Extension for tagging",
  "version": "0.1",
  "manifest_version": 2,
  "minimum_chrome_version": "29",
  "background": {
    "page": "/background/index.html"
  },
  "content_scripts": [{
    "matches": [
      "https://mail.google.com/*",
      "https://inbox.google.com/*"
    ],
    "js": ["/libs/inboxsdk.js", "/libs/alertify/alertify.min.js", "/contentScript/tag.js"],
    "css": ["/libs/alertify/alertify.default.css", "/libs/alertify/alertify.core.css"],
    "run_at": "document_end"
  }],
  "web_accessible_resources": ["/icons/tag.png", "*"],
  "permissions": ["identity", "<all_urls>", "tabs", "webRequest", "webRequestBlocking", "https://accounts.google.com/*", "https://www.googleapis.com/*", "https://mail.google.com/",
    "https://inbox.google.com/"
  ],
  "content_security_policy": "script-src 'self' 'sha256-Y+2PBkTuXdKc9Mz9jB6CV7zSLRMuViwjLM28phOgupM=' https://apis.google.com; object-src 'self'",
  "oauth2": {
    "client_id": "763145023672-gblto66pc638n485lu08visrvpocfqbs.apps.googleusercontent.com",
    "scopes": ["https://mail.google.com/",
      "https://www.googleapis.com/auth/gmail.modify",
      "https://www.googleapis.com/auth/gmail.labels",
      "https://www.googleapis.com/auth/gmail.send"
    ]
  }
}

index.html:

<!DOCTYPE html>
<html>
<head>
<title>Extension for tagging</title>
<meta charset='utf-8' />
<script src = "auth.js" </script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=checkAuth"></script>


<script src = "/libs/inboxsdk.js" </script>
<script src = "/contentScript/tag.js" </script>
</head>
<body>
<div id="authorize-div" style="display: none">
<span>Authorize access to Gmail API</span>
<!--Button for the user to click to initiate auth sequence -->
<button id="authorize-button" onclick="handleAuthClick(event)">
Authorize
</button>
</div>
</body>
</html>

auth.js:

var CLIENT_ID = '763145023672-gblto66pc638n485lu08visrvpocfqbs.apps.googleusercontent.com';
var SCOPES = [
  'https://mail.google.com/',
  'https://www.googleapis.com/auth/gmail.modify',
  'https://www.googleapis.com/auth/gmail.labels',
  'https://www.googleapis.com/auth/gmail.send'
];

function checkAuth() {
  gapi.auth.authorize({
      'client_id': CLIENT_ID,
      'scope': SCOPES,
      'immediate': true
    },
    handleAuthResult);
}

function handleAuthResult(authResult) {
  var authorizeDiv = document.getElementById('authorize-div');
  if (authResult && !authResult.error) {
    // Hide auth UI, then load client library.
    authorizeDiv.style.display = 'none';
    loadGmailApi();
  } else {
    // Show auth UI, allowing the user to initiate authorization by
    // clicking authorize button.
    authorizeDiv.style.display = 'inline';
  }
}

function handleAuthClick(event) {
  gapi.auth.authorize({
      'client_id': CLIENT_ID,
      'scope': SCOPES,
      'immediate': false
    },
    handleAuthResult);
  return false;
}

function loadGmailApi() {
  gapi.client.load('gmail', 'v1', updateLabel);
  updateLabel();
}

tag.js:

function updateLabel() {
  var request = gapi.client.gmail.users.labels.update({
    'userId': 'me'
  });
  request.execute(function(resp) {
    function whenNoneSelected(route) {
      return false;
    }

    function register(sdk) {
      sdk.Toolbars.registerToolbarButtonForList({
        title: 'General',
        section: sdk.Toolbars.SectionNames.INBOX_STATE,
        iconUrl: chrome.extension.getURL('/icons/tag.png'),
        onClick: tagThread() {
          var label = GmailApp.getUserLabelByName("General");
          var threads = label.getThreads(); // var threads = GmailApp.getThreads();
          for (var i = 0; i < threads.length; i++) {
            //add label "General" for selected threads
            threads[i].addLabel(label);
          }
          alertify.success('Threads tagged as General');
        },
        hasDropdown: false,
        hideFor: whenNoneSelected,
        keyboardShortcutHandle: null
      });
    }
    InboxSDK.load('1', 'sdk_mailtag_fd47af3e65').then(register);
  });
}

replacedtag.js:

function whenNoneSelected(route) {
  return false;
}
function register(sdk) {
  function tagThread(event) {
      alertify.success('Threads marked as General'); 
  }
  sdk.Toolbars.registerToolbarButtonForList({
    title: 'General',
    section: sdk.Toolbars.SectionNames.INBOX_STATE,
    iconUrl: chrome.extension.getURL('/icons/tag.png'),
    onClick: tagThread,
    hasDropdown: false,
    hideFor: whenNoneSelected,
    keyboardShortcutHandle: null
      });
    }
InboxSDK.load('1', 'sdk_mailtag_fd47af3e65').then(register);

Anyone with relevant solution will be greatly appreciated.

shivani
  • 21
  • 4
  • It happens when you your client id is invalid. Check my answer here : http://stackoverflow.com/questions/31693754/callback-not-called-for-chrome-identity-getauthtoken-for-self-hosted-chrome-exte/31701030#31701030. – Siddharth Nov 19 '15 at 07:04
  • Hi Sid actually I generated new client id by following the link which you have sent and after making that change I was about to logged In successfully but my doubt is that the authorization page which was displayed when I logged in for the first time was not repeated from next time onwards I tried by different mail id's also but it did not work. In the sense there is no redirecting page to login. – shivani Nov 19 '15 at 09:05
  • 1
    Yes because you are using chrome.identity.getAuthToken() which returns auth token associated with account logged in chrome browser not in gmail. Your chrome account remains same even if you log in into gmail via different accounts. If you want to get auth token from gmail account you will need to use chrome.identity.launchWebAuthFlow(): https://developer.chrome.com/apps/identity#method-launchWebAuthFlow. – Siddharth Nov 19 '15 at 09:30
  • Hi I replaced this code "chrome.identity.getAuthToken({ 'interactive': true }, function(token) { // Use the token. });" with "chrome.identity.launchWebAuthFlow( {'url': '', 'interactive': true}, function(redirect_url) { /* Extract token from redirect_url */ });" in background.js file but also I did not find any redirecting page to login – shivani Nov 19 '15 at 11:28
  • Make sure you added parameter '&prompt=select_account' in the url-to-do-auth. Also check for errors in background.js console – Siddharth Nov 19 '15 at 11:30
  • Hi I used '&prompt=select_account' in the url-to-do-auth but it did not work even I tried to replace '&prompt=select_account' with 'prompt=consent' but also it did not work. Also I did not find any errors in background.js console. – shivani Nov 20 '15 at 05:30
  • chrome.identity.launchWebAuthFlow({ 'url': 'prompt=consent', 'interactive': true }, function(redirect_url){ /* Extract token from redirect_url */ }); – shivani Nov 20 '15 at 08:32
  • That url is not even close to a valid one. Check out this answer here(how to register your app as web application to work with chrome.identity.launchWebAuthFlow()):http://stackoverflow.com/questions/25652040/chrome-extension-getting-users-email-address-who-logs-into-the-google-account . And check this Github example how to use chrome.identity.launchWebAuthFlow(): https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/github-auth – Siddharth Nov 20 '15 at 08:38
  • Hi thanks for those links I tried to follow them but it wont get compatible with the functionality which I am developing at present. So, I will keep chrome.identity.getAuthToken() itself for time-being but my doubt is that when I executed successfully with this chrome.identity.getAuthToken() for the first time the extension got authorized right. Then the functionality should work know now but even I did not find the functionality UI in the gmail interface so I am not understanding where it had went wrong. So, Can you please help me with this issue. – shivani Nov 20 '15 at 10:30
  • I had posted the issue as a query in the following link by describing it clearly in a point wise so you can also please check the issue here in the following link http://stackoverflow.com/questions/33820458/required-functionality-ui-is-not-seen-in-gmail-interface-for-the-chrome-extensio – shivani Nov 20 '15 at 10:55
  • Either use client.js for auth process or chrome.identity.getAuthToken(). You are already using client.js. So use this and auth.js as a background script .Check here(how to use client.js in background) : http://stackoverflow.com/questions/18681803/loading-google-api-javascript-client-library-into-chrome-extension. Now define the click handler on button with id="authorize-button" inside content script. Inside the onclick function send message to background script and execute your auth code as you want. – Siddharth Nov 20 '15 at 12:25
  • Hi actually I removed background.js file which contains chrome.identity.getAuthToken() and I am using client.js only for auth process as you told. So, For this I mentioned auth.js in background and I call backed that file from index.html page by mentioning it in script tag and giving authorization button code in body of html page as mentioned above in program code but when I executed this I did not find any button in gmail inbox UI for my functionality to work. Also I did not find any errors while debugging. – shivani Nov 23 '15 at 05:21
  • Hi actually when I replaced the tag.js file code with normal code which I had written only for display of button in the toolbar along with the alert message to get displayed on button click just to check where I am going wrong for the button UI to get viewed in the toolbar. At that time I was successful in viewing the button in the gmail toolbar but I am not understanding how to insert the code for the mails to get tagged. I already posted the replaced code above in program stating replacedtag.js file. Please check it. – shivani Nov 23 '15 at 06:40

0 Answers0