简体   繁体   English

Google Chrome扩展程序-页面加载后如何执行代码?

[英]Google Chrome extension - How to execute a code once page is loaded?

I'm trying to create an extension to automate some tasks. 我正在尝试创建一个扩展来自动执行某些任务。 I'm trying to load a page and then execute a code once the page has been loaded but I couldn't find the right way to do this. 我试图加载页面,然后在页面加载后执行代码,但是我找不到正确的方法来执行此操作。

custom.js: custom.js:

var func=function(){

var actualCode = '(' + function() {
    //load the new page
    window.location='http://page.com/'
} + ')();';
    // inserts the code into the current page tab
    chrome.tabs.executeScript(null, { code:actualCode})

    //--Execute this code once the page is loaded--

}

document.getElementById('btn').addEventListener("click",func);

index.html: index.html:

<!DOCTYPE html>
<html>
 <head>  
 </head>
 <body>
  <button id="btn"> BTN </button>
  <script src="custom.js">
  </script>
 </body>
</html>

To track the new page and run any logic on it, one solution could be adding this logic inside a content script file that loads at the document_end and every time you navigate to the any page using window.location , this logic will run. 为了跟踪新页面并在其上运行任何逻辑,一种解决方案是将该逻辑添加到内容脚本文件中,该文件将在document_end加载,并且每次您使用window.location导航到任何页面时,该逻辑都会运行。 You may add some conditions to make sure you logic run on the wanted pages/elements. 您可以添加一些条件以确保您的逻辑在所需的页面/元素上运行。

Am I clear enough? 我足够清楚吗?

You can use Content Scripts . 您可以使用内容脚本

Example from docs: you need to modify manifest.json to allow extension automatically inject some javascript for websites if urls are matching to the pattern. 来自文档的示例:您需要修改manifest.json以允许扩展名(如果url与模式匹配)自动为网站注入一些JavaScript。

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "js": ["myscript.js", "myscript2.js"]
    }
  ],
  ...
}

You can also define run_at property to control when the files in js are injected. 您还可以定义run_at属性来控制何时注入js中的文件。 It can be "document_start", "document_end", or "document_idle". 它可以是“ document_start”,“ document_end”或“ document_idle”。

我不确定我是否了解得很好,但是如果我了解得很好,这应该可以工作。

document.addEventListener("DOMContentLoaded",yourFunctionGoesHere)

Try using chrome.tabs.onUpdated.addListener to check if the page has been fully loaded where status is equal to 'completed'. 尝试使用chrome.tabs.onUpdated.addListener来检查状态是否为“已完成”的页面是否已完全加载。

Use the code samples which was given in this SO thread : 使用此SO线程中给出的代码示例:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {

    // execute some codes here

  }
})

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

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