本文介绍了Chrome扩展程序:如何重定向到自定义HTML页面以响应特定的Web请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个扩展程序,将所有网络流量重定向到特定的域名,例如wikipedia.org,到一个名为Whoa,bub。You的中间页面关于去维基百科,你确定吗?然后是和按钮。 如何响应特定的网址请求并替换所需的网页如果它符合在网域中使用wikipedia.org的页面的条件,那么使用自定义的一个?

使用 webRequest 功能,背景页面以及和按钮的自定义页面执行此操作。例如,在后台页面中写下类似内容:

  var URLStorage; 

if(request&&request.url)
{
if(request.type == main_frame)//在主窗口中加载新页面/站点
{
if(request.url.indexOf(wikipedia.org)> -1)
{
URLStorage = request.url;
return {redirectUrl:chrome.extension.getURL(confirmation.html)};
}
}
}
}

chrome.webRequest.onBeforeRequest.addListener(interceptRequest,{url:[*:// * / * ]},['blocking']);

这个例子并没有严格检查域名中是否提到维基百科,但为了清晰起见,我这样做了。在我的真实代码中,使用了一个特殊的类'URL'来解析传递的URL并为它的每个部分提供属性,因此可以选择性地检查它们。



code> confirmation.html 只需放置2个按钮,并将它们绑定到适当的代码,例如,如果用户回答是,则重定向到请求的网站。

  $('#okbutton')。click(function()
{
document.location.href = chrome.extension.getBackgroundPage ().URLStorage;
});

不要忘记在权限中提及webRequest和webRequestBlocking 部分清单。


I'd like to write an extension that redirects all web traffic to a specific domain, let's say wikipedia.org, to an intermediate page that says something like, "Whoa, bub. You're about to go to Wikipedia. Are you sure about this?" followed by and buttons.

How do I respond to a specific URL request and replace the desired page with a custom one when it meets the condition of being a page with "wikipedia.org" in the domain?

解决方案

You can do this using webRequest feature, a background page, and custom page with and buttons. For example, write something similar in the background page:

var URLStorage;

function interceptRequest(request)
{
  if(request && request.url)
  {
    if(request.type == "main_frame") // new page/site is loading in main window
    {
      if(request.url.indexOf("wikipedia.org") > -1)
      {
        URLStorage = request.url;
        return {redirectUrl: chrome.extension.getURL("confirmation.html")};
      }
    }
  }
}

chrome.webRequest.onBeforeRequest.addListener(interceptRequest, {urls: ["*://*/*"]}, ['blocking']);

This example does not strictly check if wikipedia is mentioned in domain, but I did this for clarity. In my real code a special class 'URL' is used which parses passed url and provides properties for every part of it, so they can be checked selectively.

In the confirmation.html just place 2 buttons, and bind them to an appropriate code, for example redirecting to requested site, if a user answered "yes".

$('#okbutton').click(function()
{
  document.location.href = chrome.extension.getBackgroundPage().URLStorage;
});

Don't forget to mention "webRequest" and "webRequestBlocking" in permissions section of your manifest.

这篇关于Chrome扩展程序:如何重定向到自定义HTML页面以响应特定的Web请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 23:13