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

标签 javascript google-chrome google-chrome-extension

我正在尝试创建一个扩展来自动执行某些任务。我正在尝试加载页面,然后在页面加载后执行代码,但我找不到正确的方法来执行此操作。

自定义.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:

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

最佳答案

要跟踪新页面并在其上运行任何逻辑,一种解决方案可以将此逻辑添加到在 document_end 加载的内容脚本 文件中,并且每次您使用 window.location 导航到任何页面,此逻辑将运行。 您可以添加一些条件以确保逻辑在所需的页面/元素上运行。

我说得够清楚吗?

关于javascript - Google Chrome 扩展 - 页面加载后如何执行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40711011/

相关文章:

javascript - 更改构造函数原型(prototype)的问题

javascript - 如何将文本文件的数据保存到变量中并在 php 文件中读取/显示它?

html - 永久更改 HTML 元素

javascript - 为什么这个 chrome.browserAction.setIcon 方法不起作用?

javascript - 尝试将消息传递到background.js时收到错误:

c# - ChromeDriver C# 禁用开发者扩展 selenium

javascript - 在 Vue.js 中更改父组件的布局

javascript - 了解 javascript 中的回调和返回函数

google-chrome - Chrome 扩展键盘命令似乎没有注册

google-chrome - Chrome 扩展程序中的接收错误 : Unchecked runtime. lastError : Could not establish connection. 接收端不存在