back button inside a iframe using history.js

2019-02-20 15:49发布

I am doing a project in RoR. That project is inside a iFrame. In that iframe have forward and back button. When I click backward button, the iframe content should go back but not the whole browser page. I am using "histroy.js" plugin. But I don't know how to use it.

My code is this:

$('#back-btn').on('click', function () {
    History.back();
});

$('#forward-btn').on('click', function () {
    History.forward();
});

$("a").click(function () {
    n = 1;
    q = n++;
    var s = $(this).attr("href");
    var o = 'History.pushState({state:' + q + ',rand:Math.random()}, "State 1", \"' + s + '\");'
    $("#z").empty().append('<button onclick=\'javascript:' + o + '\'>sds</button>');
    $("#z button").click();


    //this is for checking log
    (function (window, undefined) {

        var
        History = window.History, // Note: We are using a capital H instead of a lower h
            State = History.getState(),
            $log = $('#log');

        // Log Initial State
        History.log('initial:', State.data, State.title, State.url);

        // Bind to State Change
        History.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate
            // Log the State
            var State = History.getState(); // Note: We are using History.getState() instead of event.state
            History.log('statechange:', State.data, State.title, State.url);
        });
    })(window);
})

Note: Sometimes I am using ajax call.

Thanks for your support.

1条回答
够拽才男人
2楼-- · 2019-02-20 16:32

you may like to use the window.history object

iframe.contentWindow.history.go(-1); // back
iframe.contentWindow.history.go(1);  // forward

so your back button can be modified as \

$('#back-btn').on('click', function () {
    iframe.contentWindow.history.go(-1);
                 or
    iframe.contentWindow.history.back(); 
});

and your forward button can be modified as

$('#forward-btn').on('click', function () {
  iframe.contentWindow.history.forward();
                or
  iframe.contentWindow.history.go(1);
});

Cheers !

查看更多
登录 后发表回答