I have a chrome extension which adds a context menu item. When clicked, one of the things it needs to do is get the URL of the page that it was clicked on. This is dead easy for most pages, because you can just use tab.url in the onClicked
event.
When used on PDF documents, this is a bit more difficult because the value of tab.url
is
chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/
- the built in chrome extension which handles PDF files.
I am currently achieving this by using a content script.
In my manifest I have the following:
{
"run_at": "document_end",
"matches": ["*://*/*.pdf"],
"js": ["pdfcontentscript.js"]
}
],
and the content script gets the URL and puts it into local storage:
pdfcontentscript.js:
chrome.storage.local.set({ 'pdfUrl': document.location.href }, function () {});
The problem is that doing it like this means the extension requires the 'Host' permission, which means it takes several days to go through the store validation process. It feels like I really shouldn't need hosts permission because all I am doing is trying to get the activeTab url that the user has clicked my extension on.
The other thing I have tried was to use tabs.executeScript()
to try and execute a script to get the URL of the PDF. This works on HTML web pages, but on PDFs it throws an error "Cannot access contents of the page. Extension manifest must request permission to access the respective host" - I think the reason for this error is because of what is being explained in the comments on this post: Permissions for modifying DOM in Chrome extension context menu
I have also tried getting the url of the active tab, as follows:
chrome.tabs.query({
active: true,
currentWindow: true
}, ([currentTab]) => {
alert(currentTab.url);
});
Unfortunately, this works ok on HTML pages, but on PDFs the url is undefined
I also tried this with lastFocusedWindow: true
instead of currentWindow: true
and got the same result.
So, my question is: In a Chrome extension, when the context menu is clicked on a PDF how can I get the URL of that PDF without having to have Host permission?