谷歌chrome扩展webrequest拦截

Google chrome extension webrequest intercept

本文关键字:拦截 webrequest 扩展 chrome 谷歌      更新时间:2023-09-26

我正在尝试创建一个chrome扩展,将谷歌学者尾注文件转换为引文格式。

chrome.webRequest.onBeforeRequest.addListener(function(reqObj){
    if (reqObj.tabId != -1){
        var xhr = new XMLHttpRequest();
        xhr.open("GET", reqObj.url, true);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                parseEndnote(xhr.responseText); //Parse the endnote and create the citation
            }
        }
        xhr.send();
        return {redirectUrl : "data:text/plain;charset=utf-8,Citation%20Created"}
    }
},
{urls : ["*://*/scholar.enw*"]}, 
["blocking"]
);

问题:

我必须重定向到数据url。我希望点击动作取消

返回{cancel : true}会导致用户被重定向到" this -page- been -blocked by-an-extension generic chrome页面"

关于如何解决这个问题,有什么想法吗?

跟踪链接的过程如下:

  1. 用户对链接
  2. 进行点击(或按键)操作
  3. 为该事件运行事件处理程序代码
  4. 单击成功,浏览器对该资源发起HTTP请求
    • onBeforeRequest监听器运行
    • 其他webRequest监听器运行等

您试图在步骤2中停止单击事件,但是您的webRequest代码直到步骤3才运行。您的webRequest代码正在运行的事实意味着某些链接激活事件(clickkeypress)已经成功。

你需要在页面中注入一个内容脚本,将事件取消侦听器直接添加到你想要停止的链接中(例如,使用return falsepreventDefault)。