【问题标题】:In Chrome Extension,How to prevent page redirect when <a> tag is clicked在 Chrome 扩展中,如何防止点击 <a> 标签时页面重定向
【发布时间】:2020-01-08 02:05:41
【问题描述】:

我有一个 chrome 扩展程序。

我想要的是:

当在页面(名为 A)中单击 &lt;a&gt; 标记时,我使用 chrome.webRequest.onBeforeRequest 阻止请求。

问题是:

我尝试了{redirectUrl: 'javascript:'}{cancel: true},但页面 A 仍然重定向。

如何防止 chrome 扩展中的重定向。

manifest.json:

{
  "background": {
    "page": "background.html"
  },
  "browser_action": {
    "default_icon": "img/19.png",
    "default_popup": "popup.html",
    "default_title": "test"
  },
  "icons": {
    "128": "img/128.png",
    "48": "img/48.png"
  },
  "is_account_related": false,
  "manifest_version": 2,
  "minimum_chrome_version": "38.0.0.0",
  "permissions": ["webRequest", "webRequestBlocking", "notifications", "tabs", "storage", "cookies", "http://*/*", "https://*/*", "*://*/*"],
  "homepage_url": "xxxx",
  "name": "test",
  "description": "test",
  "version": "10.3.6",
  "content_security_policy": "script-src 'self' 'unsafe-eval' xxx 'unsafe-inline'; object-src 'self'",
  "key": "xxx"
}

背景.html

chrome.webRequest.onBeforeRequest.addListener(
        function (details) {
            console.log('========start============');
            console.log('block', details, details.url);
            console.log('========end============');
            // return { redirectUrl: 'javascript:' };
            return { cancel: true };
        },
        { urls: ["*://developer.mozilla.org/*"] },
        ['blocking']
    );

在 background.html 中,日志是正确的。但页面仍在导航

=== 更新

我发现页面使用history API 进行导航。那么有什么办法可以防止history api,比如history.pushhistory.replace

【问题讨论】:

  • 1) 显示你的代码和manifest.json,它可能有错误。 2) 页面可能有自己的点击监听器,并通过操作 location 对象导航到新 URL,您可以在 devtools(元素面板、事件监听器子面板)中检查该对象。后者可以被内容脚本使用标准事件方法(如 stopPropagation())阻止。
  • 是的,我发现页面有自己的点击监听器。但我不喜欢将 javascript 注入页面。有没有其他方法可以阻止导航请求?
  • 好吧,毕竟您的代码/清单中可能有错误。因为 webRequest 应该能够阻止任何页面启动的导航,无论其方法如何。
  • 关于您的新编辑:历史导航不是真正的导航,因此要阻止它,您必须在页面上下文中覆盖 pushState (partial example)。
  • 好的。得到它 。谢谢

标签: google-chrome-extension


【解决方案1】:

你也可以return false; 每次&lt;a&gt; 像这样点击:

for(elem of  document.getElementsByTagName("a")){
    elem.onclick = () => false;
}

【讨论】:

    【解决方案2】:

    确保您在清单中具有适当的权限,如文档中所述

    由于此函数使用阻塞事件处理程序,它需要清单文件中的“webRequest”以及“webRequestBlocking”权限。

    你也可以试试

    chrome.webRequest.onBeforeRequest.addListener(
        function(details) { return {cancel: true}; },
         {urls: ["<all_urls>"]},
         ["blocking"]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-05
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多