从chrome扩展程序监视history.pushstate

shm*_*ael 16 javascript google-chrome-extension

我正在开发Chrome扩展程序以调整Facebook.然而,支持HTML5的网站,如Facebook内醒目浏览行为要求的覆盖window.history.pushState解释在这太问题.

不幸的是,Chrome的孤立世界似乎阻止了这种覆盖.有没有其他方法来捕捉历史变化(除了民意调查document.location.href)?

phi*_*oye 7

不确定您是否尝试在background.js或content.js中执行此操作,但如果是前者,则可以使用webNavigation事件执行此操作:

您需要webNavigationmanifest.json中设置权限:

  "permissions": [
     "webNavigation"
  ],
Run Code Online (Sandbox Code Playgroud)

然后在background.js中:

  chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
        console.log('Page uses History API and we heard a pushSate/replaceState.');
        // do your thing
  });
Run Code Online (Sandbox Code Playgroud)

来源:针对webNavigation的Chrome扩展文档

  • 如果它在 content.js 中怎么办?您还需要进行 hack 吗? (2认同)

Bor*_*ris 5

是,

一种方法是创建脚本标记并将代码放在那里:

html = "window.history.pushState = function(a,b,c) { alert('Change !'); };";

var headID = document.getElementsByTagName("head")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.innerHTML = html;
headID.appendChild(newScript);
Run Code Online (Sandbox Code Playgroud)