Browser does not remember position of page last viewed - browser

I have done a few searches for this issue and I have come up empty handed. I hope somebody can clarify things for me and point me in the right direction.
Problem: I have a page that displays a list of results after submitting a search form. When a user clicks on one of the results, the browser goes to a new page showing more information about the result. When the user then clicks the 'back' button to go pack to the results, my browser reloads the page and shows the top of the page instead of the result that was last clicked.
Goal: What I would like is this: when the user click's the back button, the browser should go back to the previous page and, instead of showing the top of the page, show the page at the previous position.
Solution: I am completely lost as how this result can be achieved. Could it have something to do with javascript, or headers sent to the browsers, maybe something to do with caching.

If this is incredibly important, I'd suggest investigating the following:
add ids to each outgoing link
use JavaScript to capture the onClick for the links
when a link is clicked, redirect the user to that link's id fragment identifier, then link out as desired
When the user hits the back button, they'll return to that specific link, e.g. http://www.example.com/#link27 instead of http://www.example.com/
You may be able to get some ideas from here:
Stack Overflow:
Is it possible to persist (without reloading) AJAX page state across BACK button clicks?
YUI Browser History Manager
Ajax Patterns: Unique URLs

You can use javascript and jquery to set the scroll position of the window and cookies to store the position to scroll to. In the javascript of the page with the search results you could have something like this:
var COOKIE_NAME = "scrollPosition";
$(document).ready( function() {
// Check to see if the user already has the cookie set to scroll
var scrollPosition = getCookie(COOKIE_NAME);
if (scrollPosition.length > 0) {
// Scroll to the position of the last link clicked
window.scrollTo(0, parseInt(scrollPosition, 10));
}
// Attach an overriding click event for each link that has a class named "resultLink" so the
// saveScrollPosition function can be called before the user is redirected.
$("a.resultLink").each( function() {
$(this).click( function() {
saveScrollPosition($(this));
});
});
});
// Get the offset (height from top of page) of the link element
// and save it in a cookie.
function saveScrollPosition(link) {
var linkTop = link.offset().top;
setCookie(COOKIE_NAME, linkTop, 1);
}
// Boring cookie helper function
function getCookie(name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(name + "=");
if (c_start != -1) {
c_start = c_start + name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end ==- 1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
// Another boring cookie helper function
function setCookie(name, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = name + "=" + escape(value) +
((expiredays==null) ? "" : ";expires=" + exdate.toGMTString());
}
This assumes your search result links have class="resultLink".

The first part of the answer is that you use anchors to land on a page somewhere other than the top. So if I have this in my html at the bottom of my page:
<a name="f"></a>
then I can have the user land there by appending the anchor to the end of he url:
http://www.bullionvalues.com/glossary.aspx#f
So, if you are talking about ASP.Net you can place the anchor in a hidden field on the page info page and then read it from the search page by using: Page.PreviousPage property.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.PreviousPage != null)
{
Object o = PreviousPage.FindControl("hfAnchor");
if (o != null)
{
HiddenField hf = o as HiddenField;
Response.Redirect(Request.Url+"#"+hf.Value);
}
}
}

I fixed this issue by sending headers with php. This was my solution:
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: store, cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", FALSE);
Thanks to everybody for the help.

Related

Open new window from quick launch in Sharepoint Online

<script type="text/javascript">
//add an entry to the _spBodyOnLoadFunctionNames array
//so that our function will run on the pageLoad event
_spBodyOnLoadFunctionNames.push("rewriteLinks");
function rewriteLinks() {
//create an array to store all the anchor elements in the page
var anchors = document.getElementsByTagName("a");
//loop through the array
for (var x=0; x<anchors.length; x++) {
//does this anchor element contain #openinnewwindow?
if (anchors[x].outerHTML.indexOf('#openinnewwindow')>0) {
//store the HTML for this anchor element
oldText = anchors[x].outerHTML;
//rewrite the URL to remove our test text and add a target instead
newText = oldText.replace(/#openinnewwindow/,'" target="_blank');
//write the HTML back to the browser
anchors[x].outerHTML = newText;
}
}
}
</script>
I have this code I put in the seattle.master file before Then in quick launch when I edit links I put #openinnewwindow after the website address. On "try link" this opens the website right. My problem is when I save it. And click the link it does not open in a new window. Any ideas why this might be happening?
I realized for this code to work that I needed Publishing enabled.

Customize the quick launch items for certain pages in sharepoint

I have requirement where client wants to customize the items in quick launch for only certain
pages.So, I want to change the items in the quick launch with some other items for a few pages.(Not about cahnging the style of quick launch. Its about the replacingthe content in quick launch)
I hope using CEWP, I can achive this.But I am not much aware how to do it.
You can have two approachs here:
1) creating a webpart to replace the quicklaunch: This way you can read the Navigation from SPWeb, and build it your own.
2) Using jQuery to change the html loading the page. In this approach, I would apply a 'display:none' to quicklaunch, make the changes in html, and then 'display:block' back. The con in this solution is that you must rely on the names/titles/urls of the items, so if an admin changes, it could break it.
I had followed following steps to achive the goal
1.. Added a CEWP in the page
Created a text file with Following script and added it to shared dcouments
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function startClock(){
var div= document.getElementById('s4-leftpanel-content');
var spans= div.getElementsByTagName('span');
for (index = spans.length - 1; index >= 0; index--) {
spans[index].parentNode.removeChild(spans[index]);
}
var urls= div.getElementsByTagName('a');
for (index = urls.length - 1; index >= 0; index--) {
urls[index].parentNode.removeChild(urls[index]);
}
var pTag = document.createElement('p');
pTag.innerHTML = "HR Report";
div.appendChild(pTag);
var aTag = document.createElement('ul');
div.appendChild(aTag);
var newLi = document.createElement('li');
aTag.appendChild(newLi);
var a= document.createElement('a');
a.setAttribute('href',"url");
a.innerHTML = "report2";
newLi.appendChild(a);
//do onload work
}
if(window.addEventListener){
window.addEventListener('load',startClock,false); //W3C
}
else{
window.attachEvent('onload',startClock); //IE
}
</script>
enter code here
Paste the url text file in shared documents in CEWP as content link(Edit web part >>content link>>paste url)
Now, existing items in the Quick Launch is removed and new items are added

Chrome extension:How to get the element in the tab?

I want to assign value to the element and auto submit after page completely load.I encounter some question.
1.How to get the element in the tab?
2.How to fire submit event when assigned value?
I want to fire as the follow code:
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
var url = tab.url;
var config = null;
if (tab.status !== "complete") {
return;
}
else {
// assign value and fire submit event
}
});
Help!!
I wouldn't do it this way. Why not use jQuery in a content script and trigger your action on ($document).ready()? That way you'll have the document and can use jQuery selectors to get the elements that interest you. To submit, just get button using a selector and call click().

SharePoint: commonModalDialogClose does not close cross-domain dialog

I have a page hosted in 'virtualcasa1' domain opening a modal dialog:
var options = {
title: "Repro",
width: 400,
height: 600,
url: http://domain2:999/sites/blank/_layouts/XDomainTest/XDomainTestTarget.aspx //[1]
//url: http://virtualcasa1/sites/blank/_layouts/XDomainTest/XDomainTestTarget.aspx [2]
};
SP.UI.ModalDialog.showModalDialog(options);
And I have this code to close it:
alert(document.domain);
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancelled clicked');
If both are in the same domain (case [2] above), the dialog closes well, no issues.
But - if target page hosted in the dialog (case [1] above), dialog does NOT close :-(
document.domain above shows the correct domain where page exists.
I suspect I'm facing a cross-domain issue here (duh), but how to fix it? Or am I wrong and issue is not XDomain-related?
Thanks much!
HTML5's postMessage is your answer.
https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
Your parent window that initiates the dialog must have the following javascript:
function listener(event) {
//alert(event.data);
if (event.data == 'Cancel') {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancel clicked');
}
else {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, event.data);
}
}
if (window.addEventListener) {
addEventListener("message", listener, false)
} else {
attachEvent("onmessage", listener)
}
Javascript for OK and Cancel buttons in your popup:
<input type="button" value="OK" onclick="parent.postMessage('Message to be displayed by the parent', '*');" class="ms-ButtonHeightWidth" />
<input type="button" value="Cancel" onclick="parent.postMessage('Cancel', '*');" class="ms-ButtonHeightWidth" />
Ajay's answer from the 1st of August 2014 is good, but it needs a bit more explanation. The reason for the failure to close the dialog is simple. Cross site scripting security features of modern browsers disallow a few things, one of which is the use of window.frameElement from within the framed window. This is a read-only property on the window object and it becomes set to null (or with IE, it actually throws an exception when you try to access it). The ordinary Cancel event handlers in the modal dialog conclude with a call to window.frameElement.cancelPopup(). This will fail of course. The ordinary Save handler where the Save worked on the server side results in SharePoint sending back a single line as the replacement document, which is a scriptlet to call window.frameElement.commitPopup(). This also will not work, and it's a real pain to overcome because the page has been reloaded and there is no script available to handle anything. XSS won't give us access to the framed DOM from the calling page.
In order to make a cross domain hosted form work seamlessly, you need to add script to both the page that opens the dialog and the framed page. In the page that opens the dialog, you set the message listener as suggested by Ajay. In the framed form page, you need something like below:
(function() {
$(document).ready(function() {
var frameElement = null;
// Try/catch to overcome IE Access Denied exception on window.frameElement
try {
frameElement = window.frameElement;
} catch (Exception) {}
// Determine that the page is hosted in a dialog from a different domain
if (window.parent && !frameElement) {
// Set the correct height for #s4-workspace
var frameHeight = $(window).height();
var ribbonHeight = $('#s4-ribbonrow').height();
$('#s4-workspace').height(frameHeight - ribbonHeight);
// Finds the Save and Cancel buttons and hijacks the onclick
function applyClickHandlers(theDocument) {
$(theDocument).find('input[value="Cancel"]').removeAttr('onclick').on('click', doTheClose);
$(theDocument).find('a[id="Ribbon.ListForm.Edit.Commit.Cancel-Large"]').removeAttr('onclick').removeAttr('href').on('click', doTheClose);
$(theDocument).find('input[value="Save"]').removeAttr('onclick').on('click', doTheCommit);
$(theDocument).find('a[id="Ribbon.ListForm.Edit.Commit.Publish-Large"]').removeAttr('onclick').removeAttr('href').on('click', doTheCommit);
}
// Function to perform onclick for Cancel
function doTheClose(evt) {
evt.preventDefault();
parent.postMessage('Cancel', '*');
}
// Function to perform onclick for Save
function doTheCommit(evt) {
evt.preventDefault();
if (!PreSaveItem()) return false;
var targetName = $('input[value="Save"]').attr('name');
var oldOnSubmit = WebForm_OnSubmit;
WebForm_OnSubmit = function() {
var retVal = oldOnSubmit.call(this);
if (retVal) {
var theForm = $('#aspnetForm');
// not sure whether following line is needed,
// but doesn't hurt
$('#__EVENTTARGET').val(targetName);
var formData = new FormData(theForm[0]);
$.ajax(
{
url: theForm.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data, status, transport) {
console.log(arguments);
// hijack the response if it's just script to
// commit the popup (which will break)
if (data.startsWith('<script') &&
data.indexOf('.commitPopup()') > -1)
{
parent.postMessage('OK', '*');
return;
}
// popup not being committed, so actually
// submit the form and replace the page.
theForm.submit();
}
}).fail(function() {
console.log('Ajax post failed.');
console.log(arguments);
});
}
return false;
}
WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions(targetName,
"",
true,
"",
"",
false,
true)
);
WebForm_OnSubmit = oldOnSubmit;
}
applyClickHandlers(document);
}
});
})();
This solution makes use of the jQuery library, which our organization uses extensively. It is our preferred framework (chosen by me). I'm sure someone very clever could rewrite this without that dependency, but this is a good starting point. I hope someone finds it useful, as it represents a good two days work. Some things to note:
SharePoint does a postback on all sorts of events on the page, including putting the page into edit mode. Because of this, it makes more sense to trap the specific button clicks, both on the form and in the ribbon, rather than wholesale redefinition of, for example, the global WebForm_OnSubmit function. We briefly override that on a Save click and then set it back.
On any Save click event, we defeat the normal posting of the form and replace that with an identical POST request using AJAX. This allows us to discard the returned scriptlet when the form was successfully posted. When the form submission was not successful, perhaps because of blank required values, we just post the form properly to allow the page to be updated. This is fine, since the form will not have been processed. An earlier version of this solution took the resulting HTML document and replaced all of the page contents, but Internet Explorer doesn't like this.
The FormData api allows us to post the form as multipart-mime. This api has at least basic support in all modern browsers, and there are workarounds for older ones.
Another thing that seems to fail in the cross domain hosted dialog is the scrolling of the content window. For whatever reason, the height is not set correctly on the div with id s4-workspace, so we also set that in the solution.
EDIT:
Almost forgot. You may also need to add this control to your framed ASPX page, which can be done with SharePoint Designer:
<WebPartPages:AllowFraming runat="server"/>
I have exactly the same issue - a dialog opening a view page for an item works fine when opened from a site collection on the same web app/domain, but the Close button fails to work when opening the same item from a site collection hosted in a separate web application. I'm assuming it is a cross-domain thing so I've altered the solution to accomodate this restriction, however, I'm not 100% happy about it as it does make the overall solution a little awkward to use from a user-perspective. I've put the issue to one side for now due to project timescales, but I'm still curious as to why. The only things I can think of is the whole cross-domain thing causing it and that maybe it is there by design to prevent XSS security holes.

Disable Specific Keys in IE 6

I need to disable specific keys (Ctrl and Backspace) in Internet Explorer 6. Is there a registry hack to do this. It has to be IE6. Thanks.
Long Edit:
#apandit: Whoops. I need to more specific about the backspace thing. When I say disable backspace, I mean disable the ability for Backspace to mimic the Back browser button. In IE, pressing Backspace when the focus is not in a text entry field is equivalent to pressing Back (browsing to the previous page).
As for the Ctrl key. There are some pages which have links which create new IE windows. I have the popup blocker turned on, which block this. But, Ctrl clicking result in the new window being launched.
This is for a kiosk application, which is currently a web based application. Clients do not have the funds at this time to make their site kiosk friendly. Things like URL filtering and disabling the URL entry field is already done.
Thanks.
For what purpose do you need this? Because disabling the backspace would be hell for typing urls or emails, etc.
We could recommend other workarounds if we knew the problem better.
EDIT 1:
This website seems to have some information as to how it's done. I can't verify it currently, but I'll look into it:
http://www.ozzu.com/programming-forum/disable-key-and-back-t44867.html
Edit 2:
This website has some key codes:
http://www.advscheduler.com/docs/manual/type_sendkeys.html
It seems BACKSPACE is 08.
EDIT 3:
Found some more code for blocking, check this out:
<script type="text/javascript">var sType = "keypress";</script>
<!--[if IE]>
<script type="text/javascript">sType = "keydown";</script>
<![endif]-->
<script type="text/javascript">
fIntercept = function(e) {
// alert(e.keyCode);
e = e || event.e;
if (e.keyCode == 116) {
// When F5 is pressed
fCancel(e);
} else if (e.ctrlKey && (e.keyCode == 0 || e.keyCode == 82)) {
// When ctrl is pressed with R
fCancel(e);
}
};
fCancel = function(e) {
if (e.preventDefault) {
e.stopPropagation();
e.preventDefault();
} else {
e.keyCode = 0;
e.returnValue = false;
e.cancelBubble = true;
}
return false;
};
fAddEvent = function(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else {
obj['e'+type+fn] = fn;
obj[type+fn] = function() {
obj['e'+type+fn](window.event);
}
obj.attachEvent('on'+type, obj[type+fn]);
}
};
fAddEvent(document, sType, fIntercept);
</script>
Ok, now you should have all you need to do it. To disable backspace, the keycode is 08. You can probably just use the code I posted with slight modifications only... :\
Try it out and see if it's what you needed. (I hope you know how to use Javascript.)
You can't do it from a web page. One of the main purposes of a web browser is to protect users from the internet. They define a very specific set of things that web sites can do, and disabling buttons isn't in the list.
On the other hand, if you're a network admin and just want to mess with your users, you might be able to do it via some desktop software. But I wouldn't hold my breath.
I'm using this jQuery solution (tested on ie6 and firefox 3.6):
$(document).keydown(function(e) {
var tag = e.target.tagName;
var ro = e.target.readOnly;
var type = e.target.type;
var tags = {
INPUT : '',
TEXTAREA : ''
};
if (e.keyCode == 8) {// backspace
if (!(tag in tags && !ro && /text/.test(type))) {
e.stopPropagation();
e.preventDefault();
}
}
});
hope it helps someone

Resources