pushState change - equivalent to Chrome Extension onHistoryStateUpdated

£可爱£侵袭症+ 提交于 2019-12-01 12:30:43

That history code needs to get injected into a tab using a content script. Right now your logic says when the history event occurs, check to see if the tab URL is valid.

In Firefox, the logic will be the other way around: when a tab is opened, check if its URL is valid, and if so, then attach a script to it that will monitor for the history event. To do so you'll need to use a Page Mod.


Edit: All the code

One key concept you're missing is the difference between a content script and a main/library script. The library scripts are stored in lib and have access to all the SDK modules, but don't have access to the DOM, window object… The content scripts are stored in data, are injected into a page using the PageMod or tabs modules, can access the dom and window objects, but have no access to any SDK modules. Content scripts are essentially like the page scripts you'd attach your standard HTML page (with <script></script>) with the caveats that they can't share variables other page scripts but they can communicate with the main scripts.

The only reason I bring this up is because your initial problem was trying to access the window object from a main script and the problem in your fiddle is that you're trying to access the tabs module inside a content script. It's worth reading the topmost link in this answer if this is still confusing.

main.js

const { PageMod } = require('sdk/page-mod');

var sendXHR = function(url) {
  // Do something with the new URL
  // See Request Module docs (below) for sending XHRs from main script.
}

const pageMod = PageMod({
  attachTo: 'top',
  include: '*',
  onAttach: function(worker) {
    worker.port.on('newURL', sendXHR);
  }
});

content.js

var sendNewUrlToMain = function() {
  self.port.emit('newURL', location.href);
}

var pushState = window.history.pushState;
window.history.pushState = function(state) {
    if (typeof history.onpushstate == "function") {
        history.onpushstate({state: state});
    }
    sendNewUrlToMain();
    return pushState.apply(history, arguments);
}

window.addEventListener('hashchange', sendNewUrlToMain); 

Here are the request module docs, for making XHRs.

NB: if you don't want to use the request module (the only reason being that you already have standard XHR code for your chrome extension and don't want to take the time to learn/rewrite that code), you can send a standard XHR from the content script, but in doing so, you risk allowing the user to close the tab and thus destroy the script before your XHR callbacks are executed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!