Chrome扩展:一旦PDF Viewer(PDF.js)处理了一个PDF,就会显示一个弹出窗口

Chrome extension: Display a popup window once PDF Viewer (pdf.js) processes a PDF

本文关键字:PDF 一个 显示 窗口 扩展 一旦 Viewer 处理 js Chrome      更新时间:2023-09-26

我是pdf.js和googlechrome扩展的新手。我正在使用pdf.js在Chrome中查看pdf文件(https://github.com/mozilla/pdf.js/tree/master/extensions/chromium)。

我想实现的内容:PDF查看器(PDF.js)加载并处理我的PDF后,我想检查用户是否通过XmlHttpRequest登录到我的网站。然后我想创建一个弹出窗口,显示用户的姓名或要求他/她登录。

  1. 我添加了checkLogin();函数到以下脚本(https://github.com/Rob--W/chrome-api/tree/master/chrome.tabs.executeScriptInFrame)。

    checkLogin();打开一个新的弹出窗口(dialog.html)

chrome.tabs.executeScriptInFrame.js:

 function checkLogin() {
     chrome.tabs.create({
        url: chrome.extension.getURL('dialog.html'),
        active: false
    }, function(tab) {
        // After the tab has been created, open a window to inject the tab
        chrome.windows.create({
            tabId: tab.id,
            type: 'popup',
            focused: true,
            height: 200, width:500
        });
    });
 }
  1. dialog.html显示从dialog.js返回的消息(包含用户名或要求用户登录)

dialog.html:

    <html>
    <head><title>Dialog test</title></head>
    <body>
    <div id="output"></div>
    <script src="dialog.js"></script>
    </body>
    </html>
  1. dialog.js:

    connect();
    function connect() {    
       var xhr = new XMLHttpRequest();
       xhr.open("GET", "sendingcookies.php", true);
       xhr.onreadystatechange = function() {
         if (xhr.readyState == 4 && xhr.status ==200 ) {    
            var response = xhr.responseText;
            document.getElementById('output').innerHTML = response;
         }
       }
     xhr.send(null);
     }
    

问题:如果我插入checkLogin();在background.js中,当加载扩展插件时,脚本会运行。然而,我想在每次PDF.js加载和处理PDF时都运行这个函数。我不知道如何进行,因为我仍然熟悉PDF.js的代码。

任何关于如何正确实现这一点的提示都将非常棒。提前感谢您的帮助!

所以我想好了如何实现它。我将这个答案发布给那些可能感兴趣的人。

正如用户@Luc在线程上建议的那样,如何知道PDF.JS是否已经完成渲染,我添加了我的checkLogin();函数转换为viewer.js.中的现有函数

document.addEventListener('textlayerrendered', function (e) {
  var pageIndex = e.detail.pageNumber - 1;
  var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
//Added this code - creates popup window once PDF has finished rendering 
  if (event.detail.pageNumber === PDFViewerApplication.page) {
    checkLogin();
    function checkLogin() {
            chrome.tabs.create({
                url: chrome.extension.getURL('dialog.html'),
                active: false
            }, function(tab) {
                // After the tab has been created, open a window to inject the tab
                chrome.windows.create({
                    tabId: tab.id,
                    type: 'popup',
                    focused: true,
                    // incognito, top, left, ...
                    height: 300, width:500
                });
            });
    }
  }
}, true);

因此,当PDF完成渲染时,我的弹出窗口就会加载。非常整洁!