我的Chrome扩展弹出窗口在几秒钟后打开,与其他扩展相比,它很慢

mwyxok5s  于 2023-06-03  发布在  Go
关注(0)|答案(2)|浏览(420)

当我们点击地址栏旁边列出的extension button(URL出现的地方)时,相应扩展名的popup.html就会显示出来。(当然,根据manifest.json
当我点击lastPass时,弹出窗口立即出现,但是当我点击我的自定义扩展(只包含popup.html)时,鼠标图标变为加载1-2秒,然后弹出窗口打开。
做了一些挖掘为什么我的弹出窗口是如此之慢,谷歌集团有类似的东西

window.load=setTimeout(activate,0);

找不到任何相关文档或工作示例。
请帮助弄清楚为什么我的扩展弹出窗口如此缓慢,尽管代码只包含弹出窗口(chrome-extensions开发的初学者)。

更新

manifest.json

{
  "manifest_version": 2,

  "name": "Sample Name",
  "description": "Sample Descriptoin",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "<all_urls>"
  ]
}

popup.html

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <div>
            <label>Enter HR Password</label>
            <input type='password' id='passwd'/>
            <button id='evaluateResults'>Evaluate</button>
            <ul id='results' style='width:100px;'>

            </ul>
        </div>
        <script src='popup.js'></script>
    </body>
</html>

popup.js

var totalCorrect=0, totalWrong=0;

document.getElementById('evaluateResults').addEventListener('click',function(){
    var passwd=document.getElementById('passwd').value;
    if(passwd==='123'){     
        var strCode="var scriptOptions = {role:'blank'};";
        chrome.tabs.executeScript(null, {code: strCode,allFrames:true}, function(){
            chrome.tabs.executeScript(null, {file: "content_script_evaluate.js",allFrames:true});       
        });
    }else{
        alert("Incorrect Password");
    }
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log(request);
    var ul=document.getElementById('results');
    var li=document.createElement('li');
    li.innerHTML=request.testName+" - "+(request.testResult?"Correct":"Wrong");
    ul.appendChild(li);
});
ctzwtxfj

ctzwtxfj1#

什么工作是添加一个空的背景页。这在谷歌文档中没有解释(或者至少我没有找到),所以更多的是侥幸,但似乎起作用了。
这个想法是,插件加载一次,当你来到页面(所以之前,你甚至点击),而不是被重新加载一遍又一遍地在每次点击。
在清单中添加如下内容:

{
  //...
  "background": {
    "page": "bg.html"
  }
  //...
}

bg.html可以是一个空的HTML文件:

<html>

</html>

再一次-从来没有找到一个明确的链接或资源解释为什么这应该这样做,我不确定这是最好的做法,但它确实为我工作。

kyks70gy

kyks70gy2#

对于更新的Manifest V3解决方案,我发现您可以简单地将html文件预加载为屏幕外文档。只需在service worker或其他脚本中包含以下代码(或类似的代码)。

const preloadHTML = async () => {
    if (!await chrome.offscreen.hasDocument()) {
        await chrome.offscreen.createDocument({
            url: "index.html", 
            reasons: [chrome.offscreen.Reason.DISPLAY_MEDIA],
            justification: "Helps with faster load times of popup"
        })
    }
}

由于我怀疑这是否是屏幕外文档的预期用途,所以我为createDocument函数添加了一个任意的原因。
请注意,您需要在manifest.json中包含offscreen权限

"permissions": [
    "offscreen"
  ],

此解决方案应该可以在现在(2023年5月)起作用,因为如果您不指定AUDIO_PLAYBACK作为创建它的原因,则文档的生命周期目前是无限的。
有关详细信息,请参阅Official Chrome Offscreen reference pageChromium discussion thread的屏幕外文档生命周期。

相关问题