How to prepend Google Docs viewer URL to PDF links using jQuery?

Hey everyone! I’m working on a project where I need to open PDF links using Google Docs viewer. I’ve already set up the PDF links on my page, but now I want to use jQuery to add Google’s viewer URL in front of the existing href attributes. Here’s what I’ve tried so far:

$(function() {
  $('a[href$=".pdf"]').each(function() {
    var pdfLink = $(this).attr('href');
    $(this).attr('href', 'https://docs.google.com/viewer?url=' + pdfLink);
  });
});

This code doesn’t seem to work as expected. I think I’m close, but I’m missing something. Can anyone spot what I’m doing wrong or suggest a better approach? I’d really appreciate any help or guidance on this. Thanks in advance!

I’ve dealt with a similar issue before, and I can tell you that encoding the URL is crucial. However, there’s another aspect to consider: some users might prefer to download the PDF directly. Here’s a solution I’ve used:

$(function() {
$(‘a[href$=“.pdf”]’).each(function() {
var $link = $(this);
var pdfUrl = $link.attr(‘href’);
var viewerUrl = ‘https://docs.google.com/viewer?url=’ + encodeURIComponent(pdfUrl) + ‘&embedded=true’;

$link.click(function(e) {
  e.preventDefault();
  window.open(viewerUrl, '_blank');
});

});
});

This approach keeps the original PDF link intact but opens it in the Google Docs viewer when clicked. It’s more user-friendly and avoids potential issues with changing the href attribute directly. Just remember to test it thoroughly, especially with PDFs hosted on different domains.

Your approach is on the right track, but there’s a small issue. The Google Docs viewer URL needs the PDF link to be encoded. Try modifying your code like this:

$(function() {
$(‘a[href$=“.pdf”]’).each(function() {
var pdfLink = $(this).attr(‘href’);
var encodedLink = encodeURIComponent(pdfLink);
$(this).attr(‘href’, ‘https://docs.google.com/viewer?url=’ + encodedLink);
});
});

This should solve the problem. The encodeURIComponent() function will properly encode the PDF URL, ensuring it works correctly with the Google Docs viewer. Also, make sure your PDF links are absolute URLs, not relative ones, for this to work properly across different domains.

Yo SwiftCoder15, ur code looks solid but u might wanna try adding the ‘target’ attribute to ur links. Like this:

$(‘a[href$=“.pdf”]’).attr(‘target’, ‘_blank’);

This’ll make sure the PDFs open in a new tab. also, double-check if ur jQuery is loaded properly. sometimes that trips ppl up. good luck dude!