简体   繁体   English

Google Chrome扩展程序WebRequest拦截

[英]Google chrome extension webrequest intercept

I am trying to create a chrome extension that will convert google scholar endnote file to a citation format. 我正在尝试创建一个Chrome扩展程序,该扩展程序会将Google Scholar尾注文件转换为引用格式。

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"]
);

Problem: 问题:

I have to redirect to a data url. 我必须重定向到数据URL。 I would prefer the click action to be cancelled . 我希望取消单击动作。

Returning {cancel : true} results in the user being redirected to a "This-page-was-blocked-by-an-extension generic chrome page" 返回{cancel : true}导致用户被重定向到“此页面被扩展的通用Chrome页面阻止”

Any ideas as to how to work around this one? 关于如何解决这个问题有什么想法吗?

The process of following a link goes like this: 跟踪链接的过程如下:

  1. User performs a click (or keypress) action on the link 用户在链接上执行点击(或按键)操作
  2. Event handler code runs for that event 事件处理程序代码针对该事件运行
  3. The click is successful, and the browser undertakes an HTTP request for the resource 单击成功,浏览器对资源进行HTTP请求
    • the onBeforeRequest listeners run onBeforeRequest侦听器运行
    • other webRequest listeners run, etc. 其他webRequest侦听器运行,等等。

You're trying to stop the click event in step 2, but your webRequest code doesn't run until step 3. The very fact that your webRequest code is running at all means that some link-activation event ( click or keypress ) has already succeeded. 您试图在步骤2中停止click事件,但是您的webRequest代码要等到第3步才能运行。事实上,您的webRequest代码完全在运行,这意味着某些链接激活事件( clickkeypress )已经存在成功了。

You'll need to inject a content script into the page to add event-canceling listeners directly to the links you want to stop (eg, with return false or preventDefault ). 您需要在页面中注入内容脚本,以将取消事件的侦听器直接添加到要停止的链接中(例如,使用return falsepreventDefault )。

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

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