Sammy.js block against theft of "real links"

I recently started using knockout.js and sammy.js to upgrade my application. However, I ran into some problems.

I have some valid links on the page - users should actually navigate to that location instead of simulating navigation behavior using sammy.js . I want only hash-related links to be redirected using sammy.js, but it also intercepts links that don't have hashes.

for example, it intercepts <a href="/logout">logout</a> .

js part that performs routing:

 Sammy(function () { this.get('#/', function () { ... }); this.get('#:id', function () { ... }); this.get('', function () { this.app.runRoute('get', '#/') }); }).run(); 

I think that the part of this.get('' .. ) is the culprit that causes this behavior - I got it from the knockout.js tutorial, which says that the string is necessary so that users from another source correctly view my web page . page with code knockout.js /w/ . I want sammy.js to work only in /w/ or at least let users switch to /logout . How can i do this?

+7
source share
3 answers

It has been a while since I used Sammy, but I think you can disable this behavior with the disable_push_state parameter:

 Sammy(function() { this.disable_push_state = true; ... }); 
+10
source share

You can use the "around" function. There are many options. I suggest doing the following:

Suppose there are some URLs. When you hit this URL, you want to transfer the server to the page. For example, logout url as "/ logout".

Now make this url as follows

 "/logout?reload=true" 

So you can control by following the Sammy code

 Sammy(function(){ this.around(function(callback) { if(this.params.reload === 'true') location.replace(this.path); else callback(); }); // Your routers are going to be here }).run() 
+1
source share

I found that if I compare window.location with a copy of the window location stored at startup, I can safely escape the Sammy trap. If the base URLs match, I start the base route. If they do not match, I reload window.location and unload Sammy.js.

 function myUrl() { var url= window.location.href; if (window.location.hash) { url= url.replace(window.location.hash, ""); } if (window.location.search) { url= url.replace(window.location.search, ""); } return url; } ... Sammy(function () { var myLocation = myUrl(); ... this.get('', function () { if (myLocation === myUrl()) { this.app.runRoute('get', '#/'); } else { window.location.reload(true); this.unload(); } }); }).run(); 
0
source share

All Articles