简体   繁体   中英

URL redirect in Chrome webRequest for blocked URLs

I am creating an extension that redirects certain sites to a local extension page. In a few cases, I'd like the user to be able to go to the actual site, based on a URL parameter I add to the extension page. So the flow is:

  1. User goes to 'cnn.com'
  2. They are redirected to my extension page, which has a few links, like: cnn.com/story/page/text?showRealUrl=true
  3. When they click on this 'special' link, I want to take them to the real URL: cnn.com/story/page/text

Here's my code:

const approved = '?showRealUrl=true';
chrome.webRequest.onBeforeRequest.addListener(
    function swenNewsListener (details) {
        var i = 0;
            if (details.url.endsWith(approved) ) {
                i = i + 1; 
                var u = details.url.replace(approved, '')
                console.log(i + " actual URL: " + u );
                return { redirectUrl: u }; // this doesn't seem to work
            } else {
                console.log(i + " in ext mode");
                var baseUrl = new URL(details.url).hostname.split(".").slice(-2).join(".")
                return { redirectUrl: chrome.extension.getURL("markup/articleList.html?sourceUrl=" + baseUrl) };
            }
    },
    { urls: ["*://*.cnn.com/*"] },  
    ["blocking"]
);

But the console output is:

1 actual URL: https://cnn.com/story/page/text
0 in ext mode

And it takes me right back to the extension page instead of the real URL.

How do I get around this?

似乎没有一种直接的方法可以做到这一点,所以当我想要访问实际网站时,我最终删除了侦听器,然后在onCompleted事件触发时重新添加侦听器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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