CHROME扩展开发文档之单页面路由变化监控

首先需要在权限里申明需要用到的tab权限

{
    "permissions": [
        "tabs",
        // "storage",
        // "cookies",
        // "alarms",
        // "scripting",
        // "webRequest",
        // "webRequestBlocking",
        // "*://*/*"
    ]
}

background.js

// 监听页面url变化
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    // console.log({changeInfo, tab})
    if (!['complete', 'loading'].includes(changeInfo.status)) return false    
    chrome.tabs.sendMessage(tabId, {type:'routeUpdate', content: tab}, response => {
        console.log(response)
    });
});

contentScript.js

// 记录页面路由变化情况
let tabUpdate = 0;
/**
 * 接收bg|popup发给content-script的消息
 * message          object          消息对象
 * sender           object          发送者,含{id: "插件的ID字符串", origin: "null"}
 * sendResponse     function        消息响应,可回复发送者
.*/
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse)
{
  let {type, content} = message;

  // console.log('crx: 收到来自bg|popup的消息:');
  // console.log({message, sender});
  if (type === 'routeUpdate') {
    // 页面路由变化会有两次通知,一次加载时,一次完成时,
    // 判断是更新还是新加载,一律放在complete,
    // 因为重定向会出现多次loading,而complete仅页面加载完成才会触发
    if (content.status == 'loading') {
      // 如果页面存在重定向会出现只完成一次complete但不止一次的loading,
      // 非特殊情况不在loading判断处理,防止不准
    }
    else if (content.status == 'complete') {
      if (++tabUpdate > 1) {
        console.log('complete路由变化' + parseInt(tabUpdate - 1));
      }
      else {
        console.log('complete新开的页面' + tabUpdate);
      }
    }
  }
  sendResponse('crx: 我是后台,我已收到你的消息:' + JSON.stringify(message));
})

除了利用chrome接口能力,还可以重写history

!!重写history应该是注入到top,而注入到contentScript是监听不到的

  • 重写history
class Dep {                  // 订阅池
        constructor(name){
            this.id = new Date() //这里简单的运用时间戳做订阅池的ID
            this.subs = []       //该事件下被订阅对象的集合
        }
        defined(){              // 添加订阅者
            Dep.watch.add(this);
        }
        notify() {              //通知订阅者有变化
            this.subs.forEach((e, i) => {
                if(typeof e.update === 'function'){
                    try {
                       e.update.apply(e)  //触发订阅者更新函数
                    } catch(err){
                        console.warr(err)
                    }
                }
            })
        }
        
    }
    Dep.watch = null;

    class Watch {
        constructor(name, fn){
            this.name = name;       //订阅消息的名称
            this.id = new Date();   //这里简单的运用时间戳做订阅者的ID
            this.callBack = fn;     //订阅消息发送改变时->订阅者执行的回调函数     
        }
        add(dep) {                  //将订阅者放入dep订阅池
           dep.subs.push(this);
        }
        update() {                  //将订阅者更新方法
            var cb = this.callBack; //赋值为了不改变函数内调用的this
            cb(this.name);          
        }
    }
    var addHistoryMethod = (function(){
        let historyDep = new Dep();
        return function(name) {
            if(name === 'historychange'){
                return function(name, fn){
                    let event = new Watch(name, fn)
                    Dep.watch = event;
                    historyDep.defined();
                    Dep.watch = null;       //置空供下一个订阅者使用
                }
            } else if(name === 'pushState' || name === 'replaceState') {
                let method = history[name];
                return function(){
                    method.apply(history, arguments);
                    historyDep.notify();
                }
            }
            
        }
    }())

    window.addHistoryListener = addHistoryMethod('historychange');
    history.pushState =  addHistoryMethod('pushState');
    history.replaceState =  addHistoryMethod('replaceState');
  • 食用方法
// 使用监听
window.addHistoryListener('history', function(){
    console.log('窗口的history改变了');
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Chrome扩展是一种用于扩展Chrome浏览器功能的开发工具。严格来说,我们所说的Chrome插件应该叫做Chrome扩展Chrome扩展是在浏览器上运行的程序,可以修改和增强浏览器的功能,例如添加新的工具栏按钮、修改网页内容、处理网络请求等。 如果你对Chrome扩展开发感兴趣,你可以参考Chrome官方开发文档提供的资源。Chrome开发文档的主页是https://developer.chrome.com/extensions/devtools,其中提供了详细的开发指南、API文档和示例代码,可以帮助你开始开发Chrome扩展。 在开发Chrome扩展过程中,通信是一个重要的方面。你可能需要与浏览器的不同组件进行通信,包括与当前打开的网页进行交互、与其他扩展或外部应用程序进行通信等。你可以在https://developer.chrome.com/extensions/messaging找到关于Chrome扩展通信的详细信息和示例代码。这些资源可以帮助你了解如何在Chrome扩展中实现不同组件之间的通信。 总结来说,Chrome扩展开发是一种扩展Chrome浏览器功能的方法,你可以通过参考Chrome官方开发文档获取相关资源和指导。你还可以了解如何在扩展中实现通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【干货】Chrome插件(扩展)开发全攻略](https://blog.csdn.net/qq_34998786/article/details/121782426)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值