如何通过AJAX检测网址更改而无需在jQuery中重新加载?

时间:2016-02-26 15:14:19

标签: jquery ajax

我有一个用户脚本(用于Chrome),我用它来为我设计duolingo的练习页面。它只使用

的单行css
jQ(document).ready(function(){
    jQ('#start-button').css({"float": "left", "margin-right": "10em"});
});

这是第一次来到页面时效果很好。但他们使用Ajax来避免页面重新加载。并且网址更改,因此如果我检测到,我可以刷新css更改,而不会丢失此网站导航模式的格式。

有人碰巧知道检测它的好方法吗?

编辑:完整的用户脚本实现了几个首先指出的流行解决方案(这是不行的):

// ==UserScript==
// @name         duolingo
// @namespace    http://your.homepage/
// @version      0.1
// @description  reformat /skills to not start timed practice by default
// @author       You
// @include      /^https?\:\/\/www\.duolingo\.com\/(skill|practice)?\/?.*/
// @require      https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// @grant        none
// ==/UserScript==

window.jQ=jQuery.noConflict(true);

jQ(document).ready(function(){
    style_duolingo();
});
jQ(window).bind('hashchange', function() {
    style_duolingo();
});
jQ(document).ajaxComplete(function() {
    style_duolingo();
});


function style_duolingo() {
    jQ('#start-button').css({"float": "left", "margin-right": "10em"});
    console.log("Tampermonkey script: wrote css change");
}

编辑#2:

赏金奖励

请提供一个不加载外部库的工作解决方案(我想知道我缺少什么,而不是将其保存在黑盒子中),并使用事件解决问题(没有基于间隔的解决方案)。如果无法使用事件(奇怪),请提供更正解决方案以及未触发事件的原因。

5 个答案:

答案 0 :(得分:3)

更改网址Duolingo使用history.pushstate。我建议你galambalazs answer to similar question

这是他的代码:

(function(history){
    var pushState = history.pushState;
    history.pushState = function(state) {
    if (typeof history.onpushstate == "function") {
        history.onpushstate({state: state});
    }

    //Custom code here
    style_duolingo();

    return pushState.apply(history, arguments);
}
})(window.history);

答案 1 :(得分:1)

像这样使用:

jQ(document).ready(function(){

    jQ(window).bind('hashchange', function() {
        jQ('#start-button').css({"float": "left", "margin-right": "10em"});
    });

});

答案 2 :(得分:1)

由于您只是调整样式,因此最好使用Stylish Chrome扩展程序,以便篡改css。然后你会添加

@-moz-document domain("www.duolingo.com") {
    #start-button {
        float: left;
        margin-right: 10em;
    }
}

注意@-moz-document遵循用户类型约定,并且可导入Chrome。实际上已经有几个published userstyles for duolingo已经:)

答案 3 :(得分:0)

如果hashchange上的window事件失败,似乎还有plugin允许相同的内容。

答案 4 :(得分:0)

您可以通过检查网址并查看是否与之前的网址匹配来检查是否有任何网址更改。它可能看起来像这样:

var oldURL = window.location.url;
var newURL = oldURL;
window.setInterval(function(){
    newURL = window.location.url;
    if(oldURL !== newURL){
        //the URL has changed
        oldURL = newURL; //to prevent the above from continuously firing
    }
}, 1000);// checks every 1000 ms (1s)