Detect changes on the url

落爺英雄遲暮 提交于 2019-12-12 08:49:11

问题


I need something to detect changes on the url but the page doesn't do post back, it changes dynamically adding just the div inside the html, so the URL page is something like this

http://www.examplepage/conversations/44455

and when I click on another section of the page it it is

http://www.examplepage/conversations/44874

it changes not only at the end but like this

http://www.examplepage/settings

without doing post back and reloading the javascript so my question is, is there a way to detect those changes? and event listener but how?

I search and everyone says hash event but I don't have any value after any hash so it doesn't work

EDIT

Just for the record I have no code of the page nor I have access, I'll explain better, I am doing a background google extension and I just added a slide out to an existing page, this page changes its url the way I explained above. the url changes like every page does, but they change the div inside the html so that the page doesn't have to charge everything again


回答1:


You need to store the URL when the page loads as a starting point and check every n milliseconds for changes using setInterval then modify based on that.

The following code does this check twice a second (500ms):

// store url on load
var currentPage = location.href;

// listen for changes
setInterval(function()
{
    if (currentPage != location.href)
    {
        // page has changed, set new page as 'current'
        currentPage = location.href;

        // do your thing...
    }
}, 500);



回答2:


There is no "clean", event-based way to detect such URL changes from a content script.

They are done with history.pushState API - and using that API doesn't emit any DOM event.

Two possible indirect event-based approaches, besides the already mentioned poll-based one:

  1. An extension can override history.pushState with an injected script to additionally emit a DOM event that can be listened to in a content script.

    This approach is described in detail here.

    The downside is that, depending on the code of the page in question, the injected script may need to be injected early, needing run_at: document_start which is suboptimal for page load performance.

  2. Use a background page that listens to chrome.webNavigation.onHistoryStateUpdated event.

    If you need to detect this in a background page — perfect, you're done, without ever needing a content script.

    If you need to detect this in a content script, you can use details.tabId in the event listener to send a message to the right content script.



来源:https://stackoverflow.com/questions/34999976/detect-changes-on-the-url

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