简体   繁体   English

页面完全加载后如何执行内容脚本

[英]How to execute content script after the page is loaded completely

I'm trying to write a Google chrome extension that grabs the element in the page by its class name.我正在尝试编写一个 Google chrome 扩展,它通过类名获取页面中的元素。 The idea is to use the content script to grab these elements and pass the messages to the extensions and pop up.这个想法是使用内容脚本来获取这些元素并将消息传递给扩展并弹出。 However, my content script always end up executing before the entire page is loaded so I can't grab the elements that I want.但是,我的内容脚本总是在加载整个页面之前执行完毕,因此我无法获取所需的元素。 I try using window.loaded and document.loaded but it didn't work.我尝试使用window.loadeddocument.loaded但它没有用。 I also tried wait an interval but the script always ended up executing at the exact same stop point.我也尝试过等待一个时间间隔,但脚本总是在完全相同的停止点处结束。

// my content script // 我的内容脚本

if (document.readyState == "complete"){
    var board_name_arr = [];
    var node = document.getElementsByClassName('Board');

    for (var i = 0; i < node.length; ++i){
        var board_name = node[i].getElementsByClassName('boardName')[0].textContent;
        board_name_arr[i] = board_name;
    }

    if (Object.keys(board_name_arr).length){
        alert("found board");
    }
}

Is there a way to force it to run after ?有没有办法强迫它追赶? Or should I not be using content script approach?或者我不应该使用内容脚本方法?

Probably the page loads its content dynamically though AJAX, so the elements you want to find may be still not loaded when the document state is ready.可能页面通过 AJAX 动态加载其内容,因此当文档状态准备好时,您要查找的元素可能仍未加载。 Even if some part of content is loaded on start, more content may come later.即使部分内容在开始时加载,更多内容可能会在以后出现。 To solve this issue correctly I'd recommend you the MutationObserver techniques.为了正确解决这个问题,我建议你使用MutationObserver技术。 I used it in my Chrome extension to inject the 'Favorite' button to each Facebook post and it worked perfectly.我在我的 Chrome 扩展程序中使用它为每个 Facebook 帖子注入了“收藏夹”按钮,并且效果很好。

See the code sample:查看代码示例:

var obs = new MutationObserver(function (mutations, observer) {
    for (var i = 0; i < mutations[0].addedNodes.length; i++) {
        if (mutations[0].addedNodes[i].nodeType == 1) {
            $(mutations[0].addedNodes[i]).find(".userContentWrapper").each(function () {
                injectFBMButton($(this));
            });
        }
    }
    injectMainButton();
});
obs.observe(document.body, { childList: true, subtree: true, attributes: false, characterData: false });

Without jQuery you can do this defining a callback function on the page load event.如果没有 jQuery,您可以在页面加载事件上定义回调函数。 You can do it this way :你可以这样做:

var loadfunction = window.onload;
window.onload = function(event){
    //enter here the action you want to do once loaded

    if(loadfunction) loadfunction(event);
}

Or this way :或者这样:

window.addEventListener("load", function load(event){
    window.removeEventListener("load", load, false); //remove listener, no longer needed
    //enter here the action you want to do once loaded 
},false);

I know, this question was posted way too long.我知道,这个问题发布得太久了。 Nevertheless, hoping it would be helpful for anyone scouting like me.尽管如此,希望它对像我这样的球探有帮助。

Chrome Extension's ContentScript have an option called run_at with options: document_start , document_idle & document_end. Chrome 扩展的 ContentScript 有一个名为 run_at 的选项,其中包含以下选项:document_start、document_idle 和 document_end。 Documentation: https://developer.chrome.com/extensions/content_scripts#run_time文档: https : //developer.chrome.com/extensions/content_scripts#run_time

.
.
.
  "content_scripts": [
    {
      "js": ["PATH_TO_YOUR_SCRIPT.JS"],
      "run_at": "document_end"
    }
  ]
.
.
.

is exactly what you needed (is the partial content of manifest.json file.正是您所需要的(是 manifest.json 文件的部分内容。

Try to use Jquery尝试使用 Jquery

$(document).ready(function(){ //your code here });

http://learn.jquery.com/using-jquery-core/document-ready/ http://learn.jquery.com/using-jquery-core/document-ready/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM