Showing posts with label How-To. Show all posts
Showing posts with label How-To. Show all posts

Adding Table of Content (TOC) in Blogger.

Table of Contents in Blogger

Creating engaging and easily navigable content is important for any blogger. Long, informative articles can be a treasure trove of information, but without proper organization, they can overwhelm readers and hinder their experience. This is where the Table of Contents (TOC) comes into play, acting as a roadmap that guides your audience through your blog posts.

Adding a table of contents isn't a built-in feature for Blogger users, like on some other platforms. However, fear not! This comprehensive guide will walk you through both manual and, more importantly, automatic methods to seamlessly integrate a TOC into your Blogger blog, significantly enhancing user experience and boosting your search engine optimization (SEO).

What is a Table of Contents (TOC)?

A Table of Contents (TOC) is a list of the main sections or topics within a document, book, or webpage, usually found at the beginning. It helps readers quickly see what's covered and jump directly to specific parts. Think of it as an interactive outline or a roadmap for the content.

Simple Definition

A Table of Contents is an organized list of headings and subheadings that shows what's in a document and where to find it. Each item in the list is typically a clickable link that jumps you to that section.

Why Should You Add a Table of Contents in Blogger?

I know you guys are more interested in the "how" section of this article, but it is also important to understand "why" TOC should be part of your long blog post and how it can improve user experience and SEO.

Here are some key benefits of a Table of Contents (TOC):

  1. Improved User Experience (UX): A TOC allows readers to quickly scan the content and jump directly to the sections that interest them most. This saves time, reduces frustration, and keeps them engaged with your article. Think of it as providing instant access to the information they're looking for.
  2. Enhanced SEO: Search engines like Google love well-structured content. A table of contents helps them better understand the hierarchy and key topics covered in your post. This can lead to:
    • Improved Crawlability: Search engine bots can more easily navigate and index your content.
    • Rich Snippets (Jump Links): Google may display jump links (links to specific sections within your article) directly in the search results, increasing your click-through rate (CTR).
    • Keyword Optimization: The headings in your TOC often contain relevant keywords, further signaling to search engines the topic of your post.
  3. Reduced Bounce Rate: When users can quickly find the information they need, they are more likely to stay on your page and explore further, thus reducing your bounce rate – a positive signal for search engines.
  4. Increased Time on Page: By making your content more digestible and navigable, you encourage readers to spend more time on your page, another crucial metric for SEO.
Okay! Now that we are both aware of the benefits of using TOC, not implementing this in our blog post will be unfair for our long informative articles. Let's learn different approaches to implement this, and later you can decide which one suits best for your needs.

How To Add a Table of Contents in Blogger.

There are generally two approaches to adding a table of contents in Blogger:

  1. Manual Table of Contents: This method involves manually identifying your headings, adding unique IDs to them in the HTML editor, and then creating a list of links that point to these IDs. While straightforward, this can be time-consuming, especially for long articles, and requires manual updates if you change your headings.

  2. Automatic Table of Contents: This more efficient approach utilizes JavaScript code to automatically scan your post for headings (H2, H3, etc.) and generate a linked table of contents. This method is dynamic – if you change your headings, the TOC updates automatically.

Key Note:

While the manual TOC has its place for very short, static pages, for the vast majority of blog posts and content-rich websites, the automatic TOC is undeniably superior in terms of overall performance.


Method 1: Creating a Manual Table of Contents.

The manual TOC relies on a fundamental HTML concept called anchor links. These links allow you to jump to a specific part of the same web page. To make this work, you need two things:

  1. An ID for the target element: A unique identifier (id) attached to the heading or section you want to link to.
  2. A link pointing to that ID: An <a> tag with its href attribute set to followed by the target element's id.

Step-by-Step Guide: Manually Adding TOC in Blogger.

Step 1: Open Your Blog Post in HTML View.

Go to your Blogger dashboard and click on "Posts" in the left sidebar. Either create a "New Post" or open an existing post you want to add a TOC to. 

In the post editor, you'll see two views: "Compose view" (the visual editor) and "HTML view" (the code editor). Click on the "HTML view" tab/button. This is crucial, as you'll be editing the underlying code.

HTML View of Blogger

Step 2: Add Unique IDs to your headings.

Now, you need to identify the headings (e.g., H2, H3, H4) in your post that you want to include in your TOC. For each of these headings, you'll add a unique id attribute.

  • Locate your headings: Scroll through the HTML view and find your heading tags (e.g.,<h2>, <h3>, <h4>).
  • Add an id attribute: Inside the opening tag of each heading, add id="your-unique-id".
    • Each id must be unique within that entire blog post.
    • IDs should contain only letters, numbers, hyphens (-), and underscores (_). Avoid spaces or special characters.
    • Make them descriptive but concise (e.g., id="introduction", id="step-one", id="benefits-of-x").
Adding ID to H2

Step 3: Create a Table of Contents List.

With your headings now uniquely identified, proceed to build the Table of Contents list itself, typically placed at the top of your post. You can achieve this by typing out your desired heading titles as a bulleted or numbered list in the "Compose view." 

For each list item, select the text, click the "Link" icon in the editor, and in the URL field, type a hashtag (#) followed directly by the exact ID you assigned to that corresponding heading in Step 2 (e.g., #introduction for the "Introduction" section). Repeat this linking process for every item in your TOC until all sections are correctly connected. 
TOC link creation

Or you can use the below sample code:

Example: Paste this code where you want to add the TOC in the post with updated ID and Headings.
<div class="toc-container">
  <h4>Table of Contents</h4>
  <ul>
    <li><a href="#introduction">Introduction</a></li>
    <li><a href="#key-features">Key Features</a></li>
    <li><a href="#setting-up">Setting Up</a></li>
    <li><a href="#troubleshooting">Troubleshooting</a></li>
  </ul>
</div>

Note: The div with toc-container and h4 for "Table of Contents" are added for structure, but the core is the ul and li with anchor links.

Step 4: Style Your Table of Contents (Optional but Recommended)

To ensure your manually created Table of Contents looks appealing and seamlessly integrates with your blog's overall design, you can apply custom CSS. This step allows you to control its visual appearance, from fonts and colors to spacing and borders.

To begin, navigate to your Blogger dashboard. From there, locate and click "Theme" in the left sidebar, then click the "Customize" button.

Within the customization options, find and select "Advanced," which will then present you with the choice to "Add CSS." This is the dedicated area where you will paste your custom styling code. After inserting your CSS, click "Save" to apply the changes to your blog's theme.
Advance Setting to Add CSS

Example CSS (you can adjust colors, fonts, margins, etc.):
.toc-container {
  border: 1px solid #ddd;
  padding: 15px;
  margin: 20px 0;
  background-color: #f9f9f9;
  border-radius: 5px;
}

.toc-container h4 {
  font-size: 1.1em;
  color: #333;
  margin-top: 0;
  margin-bottom: 10px;
}

.toc-container ul {
  list-style-type: none; /* Removes default bullets/numbers */
  padding-left: 0;
  margin-bottom: 0;
}

.toc-container li {
  margin-bottom: 8px;
}

.toc-container a {
  text-decoration: none;
  color: #007bff; /* Example link color */
  transition: color 0.3s ease;
}

.toc-container a:hover {
  color: #0056b3; /* Example hover color */
  text-decoration: underline;
}

Step 5: Preview and Publish Your Post.

Click the "Preview" button in the Blogger post editor to see how your TOC looks and if the links work correctly. If everything looks good, click "Publish" (or "Update" for an existing post).

The manual method is a good way to understand how anchor links work and is suitable for occasional, shorter posts where you need precise control. However, for a scalable and efficient solution, an automatic TOC is generally preferred.

Method 2: Implementing an Automatic Table of Contents.

This method is recommended for most Blogger users as it automatically generates the TOC based on your post's headings, saving you significant time and effort in the long run. It involves adding a bit of HTML, CSS, and JavaScript to your Blogger theme.

Step-by-step Guide: Automatic Table of Contents.

Step 1: Prepare your blog post headings.

Before adding any code, ensure your blog posts are structured correctly using Blogger's heading options. The automatic script will rely on these.

When writing your posts in "Compose view," always use the built-in heading styles (e.g., "Heading," "Subheading," "Minor heading") for your main sections and sub-sections. These correspond to HTML tags like <h2>, <h3>, <h4>, etc.

Step 2: Add the HTML placeholder for the TOC.

This is where your Table of Contents will actually appear in your blog posts. You'll add a simple div element.
  1. Open or Create a Post: Go to your Blogger dashboard, then "Posts," and open the post where you want the TOC to appear.
  2. Switch to HTML View: In the post editor, click on the "HTML view" tab/button.
  3. Insert the Placeholder: Decide where you want your TOC to show up. The most common and effective place is right after your introductory paragraph, before the first main heading (<h2>).
Note: This check ensures the script only runs if you've placed the code in your post, preventing errors on pages without a TOC.

Paste the following HTML Code:
<div id="blog-toc-container"></div>

Step 3: Add the Custom CSS for Styling the TOC.

From the Blogger dashboard, click on Theme > Customize > Advanced and select the "Add CSS" option from the drop-down. Copy the following CSS code and paste it into the "Add CSS" box. You can modify the values (colors, padding, margins, etc.) to match your blog's design.

CSS Code:
/* Table of Contents Styling */
#blog-toc-container {
  background: #fdfdfd; /* Light background for the box */
  border: 1px solid #e0e0e0; /* Subtle border */
  padding: 20px;
  margin: 25px 0; /* Space above and below the TOC */
  border-radius: 8px; /* Slightly rounded corners */
  box-shadow: 0 2px 5px rgba(0,0,0,0.05); /* Soft shadow */
}

#blog-toc-container .toc-title {
  font-size: 1.25em; /* Larger title font */
  font-weight: 700; /* Bold title */
  color: #333;
  margin-bottom: 15px; /* Space below title */
  text-align: center; /* Center the title */
}

#blog-toc-container ul {
  list-style: none; /* Remove default list bullets/numbers */
  padding-left: 0;
  margin: 0;
}

#blog-toc-container li {
  margin-bottom: 8px; /* Space between list items */
  line-height: 1.5;
}

#blog-toc-container a {
  text-decoration: none; /* Remove underline from links */
  color: #007bff; /* Link color */
  font-weight: 500;
  transition: color 0.3s ease; /* Smooth hover effect */
}

#blog-toc-container a:hover {
  color: #0056b3; /* Link hover color */
  text-decoration: underline;
}

/* Indentation for subheadings */
#blog-toc-container ul ul {
  margin-left: 5px; /* Indent for H3 */
  padding-left: 5px;
}

#blog-toc-container ul ul ul {
  margin-left: 5px; /* Indent for H4 */
  padding-left: 5px;
}

Click "Save" at the bottom right of the theme customizer.

Step 4: Add the JavaScript for Generating the TOC.

This code finds headings and creates a TOC dynamically.
  1. From the Blogger dashboard, click on Theme in the left sidebar and select "Edit HTML" from the drop-down.
  2. Locate the </body> Tag: Carefully scroll down to the very end of your theme's HTML code and find the closing </body> tag. Press Ctrl+F to find the exact keyword.
  3. Paste the following JavaScript code just before the </body> tag and click on the Save icon. This ensures the entire page content is loaded before the script tries to find the headings. 
Code to add Automatic Table of Contents in Blogger

JavaScript Code:
<script>
//<![CDATA[
document.addEventListener('DOMContentLoaded', function() {
    const tocContainer = document.getElementById('blog-toc-container');

    if (tocContainer) { // Ensure the TOC container exists on the page
        const postBody = document.querySelector('.post-body, .blog-post-body'); // Adjust based on your theme's content selector
        if (!postBody) {
            console.warn("Could not find post body. TOC generation aborted.");
            return;
        }

        const headings = postBody.querySelectorAll('h2, h3, h4'); // Select heading levels to include

        if (headings.length > 0) {
            let tocHtml = '<div class="toc-title">Table of Contents</div><ul class="toc-main-list">';
            let currentH2 = null;
            let currentH3 = null;

            headings.forEach((heading, index) => {
                // Generate a unique ID for the heading if it doesn't have one
                const headingId = heading.id || 'section-' + (index + 1);
                heading.id = headingId; // Assign the ID back to the heading

                const headingText = heading.textContent.trim();
                const tagName = heading.tagName.toLowerCase(); // h2, h3, h4

                if (tagName === 'h2') {
                    if (currentH2) { // Close previous h2's ul if open
                        if (currentH3) {
                            tocHtml += '</ul>'; // Close h3 ul
                            currentH3 = null;
                        }
                        tocHtml += '</ul>'; // Close h2 ul
                    }
                    tocHtml += `<li><a href="#${headingId}">${headingText}</a><ul class="toc-h2-list">`;
                    currentH2 = headingText;
                    currentH3 = null; // Reset H3 for new H2
                } else if (tagName === 'h3') {
                    if (!currentH2) { // If an H3 appears before any H2, handle it (e.g., skip or add to main list)
                        // Optional: You could add it to the main list or skip
                        // For simplicity, we'll ensure it's nested under an H2 or add to top level if no H2
                         tocHtml += `<li><a href="#${headingId}">${headingText}</a></li>`;
                    } else {
                        if (!currentH3) {
                            tocHtml += `<ul class="toc-h3-list">`;
                            currentH3 = headingText;
                        }
                        tocHtml += `<li><a href="#${headingId}">${headingText}</a></li>`;
                    }
                } else if (tagName === 'h4') {
                    if (!currentH3) { // If H4 appears without H3, try to nest under H2, or add to top
                        if (!currentH2) {
                            tocHtml += `<li><a href="#${headingId}">${headingText}</a></li>`; // Add to main list if no H2/H3
                        } else {
                            tocHtml += `<ul class="toc-h3-list"><li><a href="#${headingId}">${headingText}</a></li></ul>`; // Create temporary H3 list
                        }
                    } else {
                         tocHtml += `<ul class="toc-h4-list"><li><a href="#${headingId}">${headingText}</a></li></ul>`; // H4s usually don't nest further
                    }
                }
            });

            // Close any open lists at the end
            if (currentH3) {
                tocHtml += '</ul>';
            }
            if (currentH2) {
                tocHtml += '</ul>';
            }
            tocHtml += '</ul>'; // Close the main list

            tocContainer.innerHTML = tocHtml;
        } else {
            tocContainer.style.display = 'none'; // Hide container if no headings found
        }
    }
});
//]]>
</script>
Key Points.
  • You may need to inspect your blog's HTML (right-click on a post, "Inspect" or "View Page Source") to find the exact class name or ID of the div that contains your main post content. If neither of these works for your theme, replace it with the correct selector (e.g., #main-post-content if your content div has an ID).
  • headings Selector: postBody.querySelectorAll('h2, h3, h4'); determines which heading levels will be included in your TOC. If you only use H2 and H3, you can remove h4.

Step 5: Test Your Automatic Table of Contents.

Go to any blog post where you've added the <div id="blog-toc-container"></div> placeholder and view it in your browser. The user can now easily navigate to different sections of the blog post.

⚠️ Troubleshoot

TOC not appearing? Double-check the postBody selector in the JavaScript matches your theme, and ensure the <div id="blog-toc-container"></div> is present in the post. Also, check for JavaScript errors in your browser's console (right-click, Inspect, Console tab).

Conclusion

The automatic Table of Contents is the clear winner for most modern websites and blogs for performance, efficiency, and sanity. It offers superior scalability, drastically reduces maintenance, and, when implemented correctly, can contribute positively to your page load speed. Invest a little time upfront in setting up a robust automatic TOC script, and you'll reap the performance and productivity benefits for years to come.

Add the Same File to Multiple Folders in Google Drive (Without Duplicating!)

Uploading Same FIle in Multiple Folders in Google Drive

We've all been there. You're deep into a project, a client presentation, or even just planning a family trip. You create a crucial document – let's say, your "Project Alpha Budget.xlsx." It's meticulously crafted, filled with vital numbers, and the result of hours of work.

Now, where does it belong? It's clearly a "Project Alpha" file, so it should be in your Project Alpha folder. But wait, it's also a key financial document, so it needs to be accessible from your Finance > Budgets folder. And what about the Client X > Deliverables folder, since this budget is also a key deliverable for them?

The common, almost instinctive, reaction for many Google Drive users is to copy the file. You duplicate "Project Alpha Budget.xlsx" into all three folders. Problem solved, right?

But what if there was a better way? Google Drive has a powerful feature that solves this exact problem: shortcuts. Think of it as creating a digital "alias" or "pointer" to your original file. When you interact with a shortcut, you're always working on the single, most up-to-date version of the document, no matter which folder you access it from.

In this guide, we'll dive deep into how to add the same file to multiple folders in Google Drive using these smart shortcuts, ensuring your digital workspace remains organized, efficient, and free from the chaos of duplicates.

Google Drive Shortcuts vs. Copies (Crucial Distinction).

Before we dive into the "how-to," let's clarify the fundamental difference between a shortcut and a copy in Google Drive. This understanding is key to truly organized file management.

What Exactly is a Google Drive Shortcut?

Imagine you have a single, physical book. A shortcut in Google Drive is like placing a sticky note in multiple sections of a library, each note saying, "This book is related to this topic – find it on Shelf B, Row 3." The notes themselves aren't copies of the book; they just point to its one true location.

Google Drive shortcut is a tiny pointer file that links directly to the original source file. It looks just like the original file in any folder you put it in, but it doesn't contain any of the file's data. Its sole purpose is to direct you to the one central version of that document.

Benefits of Shortcuts:
  • Zero Additional Storage: Shortcuts consume negligible space.
  • Always the Latest Version: Update the original file, and those changes reflect instantly across all shortcuts. You always work on the most current version.
  • Seamless Collaboration: Everyone works on the same underlying document, preventing confusion and lost work.

The Problem with Creating a "True" Copy.

Conversely, when you copy a file in Google Drive, you're creating an entirely new, independent version of that file. It's like taking your physical book to a copy shop and making an exact duplicate.

Drawbacks of Copies:
  • Wasted Storage: Each copy takes up full storage space.
  • Version Control Nightmare: Update one copy, and the others remain outdated. Tracking the "master" version becomes a chaotic mess.
  • Collaboration Headaches: Multiple independent copies make effective team collaboration nearly impossible.

How to Add the Same File to Multiple Folders in Google Drive.

Now that we understand the power and benefits of Google Drive shortcuts, it's time to put that knowledge into action. Forget the old ways of copying files; we're about to explore the smart, efficient methods that will keep your Drive organized and your files up-to-date everywhere they need to be.

Before we begin, ensure you have:
  • A Google Account: You'll need an active Google account to access and use Google Drive.
  • Access to Google Drive: Make sure you're logged in and can navigate your Drive (drive.google.com).
  • The Original File: You'll need the file you intend to add to multiple folders readily available in your Drive. Remember, you're creating shortcuts to this original file, not duplicating it.
Let's dive into the methods!

Method 1: The "Add Shortcut to Drive" Option (The Most Common Way)

This is the most straightforward and officially recommended method by Google for adding a file to multiple folders without creating duplicates. It's accessible via the right-click context menu and offers a clear path to organizing your files.

Step-by-Step Guide:
  1. Go to drive.google.com and find the original file you want to add to other folders. Right-click on this file to open the context menu.
  2. From the menu, move to "Organize," then click "Add shortcut". A dialog box will appear. Browse through your Drive's folders and select one or more destination folders where you want the shortcut to appear.
  3. Google Drive Option to Create File Shortcut
  4. After selecting your folder(s), click the "Add" button in the dialog box.
  5. Add Shortcut of File
  6. Navigate to the folder(s) where you added the shortcut. You'll see the file there, marked with a small arrow icon on its thumbnail, confirming it's a shortcut to the original.
  7. Shortcut Created in New Folders
Note: Deleting the file shortcut won't delete the file from the original source.

Method 2: The "Shift + Z" Keyboard Shortcut.

For those who prefer keeping their hands on the keyboard, the Shift + Z shortcut offers a remarkably fast way to create shortcuts. Simply select the original file, then press Shift + Z (on Windows/Chrome OS) or Shift + Cmd + Z (on Mac). 

A small dialog will pop up, allowing you to quickly browse and select the folder(s) where you want to add the shortcut, mimicking the functionality of the right-click menu but with less mouse movement. This method is a favorite among productivity enthusiasts for its speed and efficiency.

Deleting a Google Drive Shortcut

To delete a shortcut without affecting the original file:
  1. Locate the Shortcut: Find the shortcut in any folder where you've placed it (it will have a small arrow icon on its thumbnail).
  2. Right-Click and Remove: Right-click on the shortcut and select "Move to Trash" (or drag it to the Trash).
  3. Moving Google Drive Shortcut to Trash
  4. Confirmation: The shortcut will be moved to your Trash. The original file remains safely in its original location, and any other folders where other shortcuts to it exist. You can then empty your Trash to permanently delete the shortcut.
⚠️ Warning

If you delete the original file from its source location, all shortcuts pointing to that file will break. The shortcuts will no longer be able to open the file. When you try to click them, you'll receive an error message indicating that the original file cannot be found or has been deleted.

You cannot restore the original file by interacting with a broken shortcut. If it hasn't been permanently deleted, you must go to the owner's Trash to restore it.

How To Audit File Sharing of Personal Google Drive.

Google Drive Auditing

We all use Google Drive’s file-sharing feature so frequently that it's easy to lose track of who has access to what. Over time, we may forget which files or folders we’ve shared and what level of access others have, especially with old clients, colleagues, or friends we’re no longer in touch with. 

Imagine if one of those shared files contains sensitive or confidential information, and it’s still accessible to someone who no longer needs it. That was exactly the situation I found myself in recently. So, I decided to create an audit log to track everything. It was a tedious and time-consuming process, but I can't do this every time I share some files with someone, so I decided to automate this task. Let's learn how?

Audit Google Drive File Sharing in Google Sheets.

There is no direct method for storing Google Drive file-sharing logs, so we are going to use Google App Script to write our own custom code to store all the required details directly inside a Google Sheet.

In this process, we will automatically scan your drive for all the files to get the required details like file name, file type, file path, file owner, link, type of access, user IDs, shared date, and last modified date. 

After collecting all these details, we will store them inside a clean new Google Sheet. At the end, we will set a trigger so our code will perform this activity every week to update your Google Sheet with new records.

Note: If you are using a custom domain with the premium version of Google Workspace that you can use this feature for free by using the Add-on available in Google Marketplace.

Here is a step-by-step process for automating auditing Google Drive Files.

Step 1: Create a Google Sheet for Audit Logs.

Open a new Google Sheet in your Google Drive and name the sheet as well as the first tab of the sheet. In my case, the sheet name is "Audit_Sheet" and the sheet's first tab name is "Audit". The sheet name can be anything based on your choice.

In the top-right corner of the sheet, click on the share button drop-down and copy the link. Keep this link handy, as we are going to use this link in our App Script Code.

Copy Google Sheet Link

Step 2: Open Google App Script Code.

In the sheet, click on Extensions > App Script. A new window will open with the Google App Script code editor. Make sure that your app script page is logged in with the same ID for which you want to audit file sharing details.

Opening Google App Script
⚠️ Warning

If you're encountering a "400 Bad Request" error when running your Google Apps Script, it may be due to a mismatch between the Google account currently active in the browser and the one used to authorize the script.

Google Apps Script tends to "remember" the account that was used the last time you accessed the Script Editor. If you're now opening or running the script using a different account in the same browser session, the script can fail to authenticate properly, resulting in this error.

Step 3: Write Google App Script Code.

Copy and paste the full code into the Google Apps Script Code Editor, then click on “Untitled project” at the top left and give your project a meaningful name (e.g., “Drive Sharing Audit Tool”). In the second line of the code, replace the placeholder with the link to your Google Sheet where you want to store the audit logs. In the fourth line, enter the name of the first sheet (tab) in that Google Sheet, which you can find in the lower-left corner of the spreadsheet (e.g., “Sheet1” or “AuditLog”).

Script Code:
function scanAllDriveFilesToSheet() {
  const sheetUrl = '<Paste_Google_Sheet_Link_Here>';
  const ss = SpreadsheetApp.openByUrl(sheetUrl);
  const sheet = ss.getSheetByName("<Paste_Sheet_1_Name_Here>");
  sheet.clearContents(); // Optional: clear old logs

  // Set headers
  sheet.appendRow(["File Name", "File Type", "File Path", "Owner", "Link", "Access Type", "User IDs", "Shared Date", "Last Modified"]);

  const files = DriveApp.getFiles();
  while (files.hasNext()) {
    const file = files.next();
    const fileName = file.getName();
    const fileType = file.getMimeType();
    const filePath = file.getParents().hasNext() ? file.getParents().next().getName() : "Root";
    const owner = file.getOwner() ? file.getOwner().getEmail() : "Unknown";
    const url = file.getUrl();
    const lastModified = file.getLastUpdated();
    const sharedDate = file.getDateCreated();
    const viewers = file.getViewers().map(u => u.getEmail()).join(", ");
    const editors = file.getEditors().map(u => u.getEmail()).join(", ");
    const access = (editors ? "Edit: " + editors : "") + " | View: " + viewers;

    sheet.appendRow([fileName, fileType, filePath, owner, url, access, viewers + " " + editors, sharedDate, lastModified]);
  }
}

Step 3: Give Permission to Run the Script.

After making all the required changes to the script, click the Save icon and then click the Run ▶️ button to execute the script. If this is your first time running an Apps Script, Google will prompt you to authorize the script to access your Google account. This access is necessary for the script to read and write data in your Google Drive in order to perform the audit.

App Script Code to Audit Google Drive
When you click "Review Permissions", a pop-up window may appear saying "Google hasn’t verified this app". This is normal for custom scripts. Click on Advanced, then select "Go to <Project_Name>" (your project name will appear there). 

Providing permission to App Script

Google will then ask you to review and approve access by checking the required boxes. Select both the checkbox and click on Continue. This is a one-time, safe process and ensures the script can function as intended.

Code will start executing and you can open your Google sheet to see the updated audit logs for the the files present in your Google Drive.

Auditing in Google Sheet

Step 4: Schedule the Automation.

If you don't want to run the Script every time to see the updated details, then you can schedule this script to run automatically. To schedule your Apps Script to run weekly, open the Script Editor and click on the clock icon 🕒 in the left toolbar (called Triggers). Click "+ Add Trigger", choose the function you want to run, set the event source to Time-driven, and then choose time based trigger as "Week timer" and select the desired day and time.

Once saved, the script will automatically run every week based on your selected schedule and no manual execution needed.

Adding Weekly Trigger to App Script

⚠️ Important: This script reads sensitive Drive data, so do not share your script with unknown users or publish it without a proper security review.

I hope you find this method helpful for Auditing Google Drive Files. It is specifically useful for someone using their Google Personal Account to manage everything.

Tip: If you ever make changes to your script (like updating logic or the linked Sheet), don't forget to re-save and re-authorize the script if needed. Also, it's a good practice to occasionally check the Executions log under Apps Script → Executions to ensure the script is running correctly on schedule and handling all files as expected.

How To Transfer Ownership of a File in Google Drive.

Transfer Ownership of Google Docs

Last month, I was wrapping up a freelance project I led for several months. All the project-related documents, reports, and shared resources were stored in my Google Drive. However, since the project was about to end, I decided to share all the related files with my client so she could take care of it further. 

Simply giving her an editing option wasn't enough, I need to give her full ownership of the files. That's when I discovered how to transfer ownership of files in Google Drive.

Transfer Ownership of a File in Google Drive.

Transferring Ownership ensures that the new person has full control over files just like you. Here's how you can do it step-by-step using your personal Google account.

Step 1: Open Google Drive and locate the file.

Go to drive.google.com in any browser where you're signed into your personal Google account. Navigate through your folders or use the search bar to find the specific file you want to transfer.

Step 2: Right-click the file and choose "Share."

Once you’ve found the file, right-click on it. From the context menu that appears, click on the “Share” option. This will open a sharing settings dialog where you manage access and permissions.

Share G-Drive File

Step 3: Add the person you want to make the new owner

If the intended new owner isn’t already listed, type their email address in the “Add people and groups” box at the top. Set any type of access you want (Viewer, Commenter, or Editor) and give a meaningful message in the message box. Then click “Send” to share the file with them. Make sure you’re entering a valid Google account email.

Share Google Drive Files

Step 4: Change their role to ‘Owner’

After the person has been added (or if they were already there), locate their name under the “People with access” section. Click the drop-down arrow next to their current role (e.g., Editor) and choose “Transfer ownership.”

Transfer Ownership

Step 5: Confirm the transfer

A pop-up will appear with a warning saying that "You'll be the owner until this person accepts ownership."Click on the Send Invitation button in the pop-up, and the user will get an email to accept the ownership of the file.

Send Invitation
Note: Once the ownership is transferred to the new user, you will still hold Editor access until the new owner removes you or makes changes to your access. You won't be able to revert the ownership again.

Step 6: Email Sent to New Owner.

The new Owner will receive an email invite to accept ownership of the shared file. The user can Accept or Decline the request based on their choice. Once accepted, complete ownership will transfer to new user.
Email Send to New Owner

Note: In personal (free) Google accounts, you cannot directly transfer ownership of a folder. Google only allows the transfer of ownership of individual files, not folders. But there are many alternative ways to transfer ownership of an entire folder and its content that we are going to learn in the next part.

Transfer Ownership of Entire Folder in Google Drive.

If you are using a free personal Google account, then you can transfer ownership of the folder to any other user, but even after that, you will still own the subfolder and files within it. There is no direct approach to transfer the ownership of the entire folder with its content in the free version of the Google account, but you get this option in the premium version of Google Workspace.

Oh, does it mean that I need to pay a premium to use this feature? Well, not really, there are a few alternative methods that we can use to achieve our goal. Let's learn a few of them here.

Method 1: Transfer Ownership Manually.

Step 1: Transfer Ownership of the Folder.

In this method, you need to transfer ownership twice to the new user. First, you have to transfer the ownership of the Folder by following the same steps that we have performed above for a single file.

Step 2: Transfer Ownership of all SubFiles.

Once the folder ownership is transferred to the new user, you can open the folder and check that you are still the owner of the entire content present in it. Press Ctrl + A from your keyboard to select files at once and repeat the first step to transfer ownership of all the selected files in one go.

Transfer Ownership of all Files at Once

Step 3: The New Owner receives an email.

The new owner with whom you want to share all the files will receive an email with a list of files and a Respond button, which will redirect the user to Google Drive to review and accept the ownership of the files.

Email Send to New Owner

Step 4: Accept Ownership of all shared Files.

When the new owner opens the folder, they can still see your name as the owner of the files present inside. The user will get two options: review each file one by one and accept the ownership, or select all entire files altogether and accept the ownership of all the files. Ask the new owner to follow the steps shown below:

To accept ownership, press Ctrl+A to select the file and click on the Share+ icon. You will get a pop-up with an "Accept Ownership?" button next to your User ID.

Accept Ownership of Entire Folder

Note: If the folder contains another subfolder with more files inside it, then you need to repeat the same steps 1 and 2 again to share the ownership of the files present in subfolders. You also need to repeat the same steps if more files get added inside that folder.

If you use Google Workspace, you can instead move files into a Shared Drive, where ownership belongs to the team. The above methods are good if you are handling everything by yourself.

How To Share Google Drive Documents With View-Only Access.

Share Google Drive File With View Only Access

Google Drive is a powerful tool for storing and sharing files online, whether you're working on a project, organizing personal documents, or collaborating with others. But not every file needs to be edited by everyone. Sometimes, you just want to share a folder so others can view the contents without being able to change anything. That’s where view-only access comes in handy.

You can restrict any external user from editing your Google Drive document before sharing it for team activities or collaborations. To prevent accidental changes, you can also set the document to view-only mode for everyone, including yourself. 

Let's learn both methods to make our documents and files more secure and safe from any kind of accidental editing.

Share Google Drive Documents With View-Only Access.

To follow this tutorial, all you need is an active Google Account and a document which is already been created and uploaded to Google Drive.

Step 1: Open Google Drive.

To begin, open your preferred web browser and go to https://drive.google.com. If you're not already signed in, you’ll be prompted to log in to your Google account. Once signed in, you'll land on the Google Drive homepage, where all your stored files and folders are displayed.

Step 2: Locate the Document You Want to Share

Scroll through your list of files, or use the search bar at the top to quickly find the document you intend to share. Once you locate it, you can either right-click on the file and select “Share” or open the document first and then click the “Share” button located in the top-right corner of the screen.

Google Drive Document Sreenshot

Step 3: Share with Specific People as Viewers

In the sharing dialog box that appears, you will see a field labeled “Add people and groups.” Type the email address of the person or group you want to share the document with. After entering the email, a drop-down menu will appear where you can select their permission level. 

Choose “Viewer” to ensure they can only view the document, but cannot comment on or edit it. Once done, click the “Send” button to share the document with them.

Adding Email id to share Google Docs

Step 4: Share via a View-Only Link (Optional)

If you prefer to share the document via a link rather than individual email addresses, look toward the bottom of the sharing dialog box. Under “General access”, click the dropdown that may say “Restricted” by default. Change it to “Anyone with the link”.

Once you do that, another dropdown will appear beside it—make sure it is set to “Viewer.” Then click “Copy link” to copy the shareable URL and send it via email, chat, or wherever needed.

Sharing Google Drive Doc Link

Pro Tip:
 Before sending or sharing the link, always double-check the access level to make sure the document is not mistakenly being shared with editing or commenting privileges.

Alternative way to Set Everyone's Role To view-only access.

First, open the sharing settings for the document using the same steps described above. For each listed user, including yourself, make sure the access level is set to “Viewer.” Click the dropdown beside each name and manually change the role if needed. Once this is done, no one will be able to modify the document in any way, but they can only view its content.

Changing Document Role to Viewer

Change Editing To View-Only Access in Google Docs.

There might be a possible scenario that you have already provided Editor access to many users for one Google Document, and now you want to change all the access to Viewer (View-Only) access. You can follow the above method to change the access type for each user ID one at a time, or there is a quick alternative way to do so by using Google App Script.

Changing Google Drive Document Permission Using Google App Script.

Step 1: First, go to https://script.google.com and click on "New Project" to create a blank script editor. This is where you'll write the automation code. Inside the script editor, paste the following code:
function restrictEditingToViewOnly() {
  var fileId = 'YOUR_FILE_ID_HERE'; // Replace with your actual fileID
  var file = DriveApp.getFileById(fileId);
  
  var editors = file.getEditors();
  
  for (var i = 0; i < editors.length; i++) {
    var userEmail = editors[i].getEmail();
    file.removeEditor(userEmail);
    file.addViewer(userEmail);
    Logger.log("Changed " + userEmail + " to viewer.");
  }
  
  var myEmail = Session.getActiveUser().getEmail();
  if (myEmail !== file.getOwner().getEmail()) {
    file.removeEditor(myEmail);
    file.addViewer(myEmail);
    Logger.log("You (" + myEmail + ") are now a viewer.");
  } else {
    Logger.log("You are the owner transferring ownership manually if needed.");
  }
}

Step 2: Replace 'YOUR_FILE_ID_HERE' with the actual file ID from your Google Drive document URL. This ID is the long string found in the URL of the file, typically located between /d/ and /edit.
https://docs.google.com/document/d/1XiYBcFw4VTHOmaD1pMmMTNlt2btERcxe0us3pHR4D4tNs/edit?usp=sharing

Step 3: Give your Project a good name and click the Save icon to save your project with the Script.

Step 4: Now, click the Run button (the triangular ▶️ icon) to execute the function. The first time you run the script, Google will prompt you to review and authorize the required permissions. Click on Review Permissions.
Google Script App

Step 5: If you are running Google App Script for the first time, you will get a pop-up saying "Google hasn't verified this app." You need to click on "Advanced" to open the advanced settings, click on your Project name, and provide all the required permissions to run the app.
Advance Setting for Google App Script

Step 6: You need to give your script permission to access your Google Account and select the checkbox shown below so the script can make the required changes in your Google Drive Document settings. Click on Continue to save to proceed.
Google Drive Permission
Step 9: After the script runs, all existing editors will be converted to viewers, and your own access will be downgraded unless you are the owner.

Note: Google doesn't allow you to remove your own access if you're the owner. You must transfer ownership manually through the Drive UI.

Be cautious with this script, especially if you choose to remove your own editing access. If you're the file owner, Google will not allow you to remove your own access via script, and you must have to transfer ownership manually through the Drive interface. For safety, it is always recommended to test this script on a duplicate file first to avoid losing access to important content.

DON'T MISS

AI
© all rights reserved
made with by WorkWithG