【问题标题】:monitoring history.pushstate from a chrome extension从 chrome 扩展监控 history.pushstate
【发布时间】:2011-06-06 11:47:24
【问题描述】:

我正在开发一个 Chrome 扩展来调整 Facebook。但是,在 Facebook 等支持 HTML5 的网站中捕获浏览操作需要覆盖 window.history.pushState,如 in this SO question 所述。

不幸的是,Chrome 的孤立世界似乎阻止了这种覆盖。有没有其他方法可以捕捉历史变化(除了轮询document.location.href)?

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

    基于@Boris 的回答:继续默认操作,保存对原始 pushState 函数的引用,然后调用它:

    var headID = document.getElementsByTagName("head")[0];         
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = chrome.extension.getURL('script.js');
    headID.appendChild(newScript);
    

    script.js:

    window.history.pushState = (function(nativePushState) {
        return function(a,b,c) {
            // Do something
            nativePushState.apply(this, arguments); //Continue by calling native history.pushState
        };
    })(window.history.pushState)
    

    【讨论】:

      【解决方案2】:

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

      您需要在ma​​nifest.json中为webNavigation设置权限:

        "permissions": [
           "webNavigation"
        ],
      

      然后在background.js中:

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

      来源:Chrome Extension docs for webNavigation

      【讨论】:

      • 如果在 content.js 中呢?你还需要破解吗?
      【解决方案3】:

      是的,

      一种方法是创建一个脚本标签并将您的代码放在那里:

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

      【讨论】:

      • 如果要拦截pushstate命令怎么办,做点什么,然后让pushstate命令正常完成,上面给出的例子似乎拦截pushstate很好,但实际上并没有执行pushstate之后的命令,你将如何实现?
      • 在这里找到了一个解决方案,但不确定它是否适用于 chrome:stackoverflow.com/questions/4570093/…
      • 自从发布答案后,这是否停止工作,或者是否有一些权限等被遗漏...?
      • 这不起作用。 Chrome 扩展(内容脚本)虽然可以访问 DOM,但无法访问页面的变量范围。
      猜你喜欢
      • 2014-10-27
      • 2013-11-30
      • 1970-01-01
      • 2013-05-23
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      相关资源
      最近更新 更多