Home > other >  Window title is not changed after pdf is loaded
Window title is not changed after pdf is loaded

Time:10-02

I'm creating a chrome extension which changes the title of some pdf page, for instance https://arxiv.org/pdf/2005.01463v2.pdf.

The code works fine before the pdf is loaded, but when the pdf is fully loaded the window's title is changed back to the pdf name (instead of my title) and using document.title = "cool title" or Chrome messages to background.js does not work.

However doing a manual document.title = "cool title" from the console in a given pdf page works well.

// content_script.js
const makeTitle = (time) => {
    setTimeout(() => {
        title = "cool title"
        console.log("Updating pdf title");
        chrome.runtime.sendMessage({ type: "update-title", options: { title } })
        window.document.title = title;
    }, time)
}

makeTitle(0)
makeTitle(1 * 1000);
makeTitle(5 * 1000);
makeTitle(10 * 1000);
makeTitle(20 * 1000);
makeTitle(60 * 1000);
makeTitle(5 * 60 * 1000);
// background.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log("Executing background message")
    if (request.type == "update-title") {
        const { title } = request.options;
        chrome.tabs.executeScript(sender.tab.id, { code: `document.title = "${title}"` });
    }
});

I have to use those setTimeout because I cannot detect if a pdf is done loading. makeTitle works fine before the pdf is loaded, but not after and I'd like to solve this. Thanks!

PS: I know there's a duplicate title change, it's just none of those 2 strategies work

CodePudding user response:

It's a bug in Chrome. It sets the title internally and ignores DOM title element.

The workaround is to use chrome.tabs.onUpdated to set an empty title, then set the intended one.

background.js

const title = 'foo';
chrome.tabs.onUpdated.addListener((tabId, info, tab) => {
  if (info.title && info.title !== title && tab.url.endsWith('.pdf')) {
    chrome.tabs.executeScript(tabId, {
      code: `document.title=''; document.title="${title}"`,
      runAt: 'document_start',
      // runs immediately if this change occurs before DOMContentLoaded
    });
  }
});

There's another bug in Chrome: it shows the built-in title intermittently when you switch to another tab and back. This particular bug seems to be fixed in the upcoming "unseasoned" PDF viewer, which can be enabled currently via chrome://flags/#pdf-unseasoned

  • Related