Run javascript on website after refreshing - javascript

What I would like to achieve is this:
refresh website
run my javascript script on it (just as if I put it in Chrome console).
Question is: how to achieve it?
I can also use PHP for this (set server on my computer that wil be redirecting to the desired website and execute my javascript program on it).
Some example of functionality I want to achieve:
Go to stackoverflow.com -> click StackExchange (you can see it in the top left corner, it can be accessed by a querySelector() in JS) -> refresh stackoverflow.com -> click StackExchange again -> repeat...

If you want to refresh the page behind a DOM element click, you can attach an event handler to the element and then in your event handler execute location.reload() to reload the page.

//When the document has loaded, call the function
document.addEventListener("DOMContentLoaded", function(event) {
if(window.location.hash == "#page"){
console.log("Page reloaded!");
}else{
console.log("Page has a new hit!");
}
});
You can use DOMContentLoaded event listener to solve your problem.

You can do something like this -
var value = localStorage.getItem("logdata");
if(value != null) {
eval(value);
logdata();
}
And try to add logdata to localStorage from console.
Example - localStorage.setItem("logdata", "var logdata = function(e) { console.log('data logged.'); }");
Now when you load the page, logdata function will be called and you can have your code executed.

Related

How to fix getting the same document element 'meta' in Google Chrome Extension

I'm developing a new Chrome extension, that return meta of a website. My problem is that I have always the same result, even if the content of web page change. To get the correct and actual meta elements I must to refresh the tab (F5).
The code of my button is :
chrome.tabs.executeScript({file: 'app/js/get_metas.js'});
And the code of my get_metas.js is :
document.head.addEventListener("DOMContentLoaded", getMeta(), true);
function getMeta() {
const meta = document.head.querySelector("meta[property='****']").getAttribute("content");
alert(meta);
}
The result is always the same, I must refresh the page with F5 to get the actual meta element.
If you enter following code in your console you will see the alert immediately:
document.head.addEventListener("DOMContentLoaded", getMeta(), true);
function getMeta() {
alert("test");
}
Reason is that the function will be called immediately. To change that remove the (), and also I believe the event is fired on the document itself (I'm not sure the event traverses down the whole document and the useCapture=true would work). So use something like:
document.addEventListener("DOMContentLoaded", getMeta, true);
It will still only fire once when document is loaded. If you need to run the function after some other event you'd need to add a listener for that event.
If you want to call your function after a change to the document (including ajax navigation) you could look into using Mutation Observers.

How can I detect page navigation without reloading?

I have script, what work one time when window loaded, it work on this page, but site use some navigation links what not fully reload page (see this answer for example: Modify the URL without reloading the page). How can I detect that and run my script again?
I have one idea: storing URL (without anchor) in variable and check it periodically with current url, but I think this is bad solution. May be you know better one?
JavaScript or JQuery is possible to use.
Use window.onpopstate or window.onpushstate if u are using pushState or replaceState ( from ur given example).
ex:-
To Navigate Without reload ( you already did this )
// Your code to fetch new URL body and title
// update the DOM then use following code to update URL also (don't use location.href, otherwise the page reloads)
// sorry u already know this because u provided the example ;)
let data = { title : "Current Title",
body : document.body.innerHTML" } // to store current page data
window.history.pushState(data, 0, "newURL");
To detect navigation ( i.e., you wanna do )
window.onpushstate: when above code runs for navigation to a new url and load new content without reload ...
window.onpushstate(function() {
// detects ur navigation
})
window.onpopstate: when you press back button
window.onpopstate(function (e) {
let { data } = e.state;
// data object that u gave in pushState method when u called ur last / latest pushState method...
// use this data to retrieve previous data content and title
let { title, body } = data;
document.title = title;
document.body.innerHTML = body
})
for more detail mdn docs
That's because the new pages are either
1 ) Already at the ready and simply being brought in-sight by jQuery
2 ) Ajax called in.
If you scout for your navigation (the links you click on to go to the other page), you should find click me or so.
If you look for wherever this is is bound (i.e.: $('#navigation a').on("click", function(){});, you can simply wrap your script within a function, and trigger this function together with loading the new page every time. (after it, obviously).
I wish I could be more clear, but you did not provide any code yourself, so I have absolutely no idea of what kind of example I should be giving here.
-- the point: Those page changes are triggered by something in your javascript. Find the trigger that makes the page-change happen, and simply insert myCustomFunction();.
If you want to make your bindings update with a new DOM, you could use this:
function setBindings(){
//removing the old bindings prevents the "click" from triggering twice.
$('a').off("click");
$('a').on("click", function(){
//load page and such here
//Apply script you want to run here
setbindings(); //rerun the function to set the bindings.
});
}
I think you are looking for hashchanges you can listen to this event onhashchange
window.onhashchange = function(e) {
var sublink = window.location.hash.substring(1);
//do your thing here
}
You can also check what updated the url after the hashchange
var sublink = window.location.hash.substring(1);
I think the URL of script is cached,do you used Ajax get method?if it is,please
like this write url "wwww.baidu.com?"+Math.random();if not is ,in the firefox ,you can used pageshow event.

Prevent back button from going back to previous page for an ID

Using the following function to prevent users from going back to previous page if the page they are on currently has the id #home. But this function doesn't even fire off. No alerts. Nothing wrong with the link to script file as I have other scripts running fine on that file.
document.addEventListener("backbutton", function (e) {
alert("Back button pressed");
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
var activePageId = activePage[0].id;
alert(activePageId);
if (activePageId == 'home') {
e.preventDefault();
}
}, false);
Unless you have created a custom event there is no onbackbutton event I know of. You are after onbeforeunload
Clients don't like it when you block navigation. You should consider other solutions to you problem rather than block navigation. Sure as .... the next thing the client will do is close the tab and a good chance you will never see a session with that client again.

asp.net javascript .click() event not firing on server

I have the following code which is working fine on the development machine. But, when I deploy it to IIS, the .click() does not fire.
I have drop down box, when a status is selected, I add the following code to open up a RadWindow
if (ddlStatusID.SelectedValue.ToString() == "2")
btnUpdateStatus.Attributes.Add("onclick", "return OpenWindow2('" +
ResolveUrl("~/Request/AddBillableTime.aspx? RequestId=" + RequestId.ToString()) +
"','650','320');");
else
btnUpdateStatus.Attributes.Add("onclick", "");
In the popup page, when the user clicks on a button I add do the following
ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow",
"ClosePopup();", true);
This is the ClosePopup javascript.
function ClosePopup() {
//debugger;
alert('This is before closing the window');
var oWindow = GetRadWindow();
oWindow.argument = null;
oWindow.close();
alert('This is after closing the window');
oWindow.BrowserWindow.ButtonClick();
}
In the main window, I have following javascript, which is invoked in the last line of the above javascript.
function ButtonClick() {
//debugger;
alert('This is before button click!');
var btnUpdateStatus =
document.getElementById('ctl00_ContentPlaceHolder1_btnUpdateStatus');
alert('This is getting the button!');
btnUpdateStatus.setAttribute("onclick", "");
alert('This is setting the button!');
btnUpdateStatus.click();
alert('This is after clicking the button!');
}
I have used the alerts to check how far the javascript function is executed.
The entire functionality is working fine when I run it using Visual Studio and also when I host it in my local IIS server. But, when I deploy it to the server, the click() event stops firing.
Please let me know if there is anything wrong in the code.
I didn't had time to look into this issue for some as I was assigned to a new task. But had to fix it once I was back in the same task. I got some help from a friend of mine to fix the issue. I had to change the current logic a bit and have explained the solution below.
I changed the ButtonClick function as below to create a manual post back to the page using the __doPostBack function.
function ButtonClick() {
__doPostBack('btnUpdatePage', '');
return;
}
I handled the post back from the Page_Load method of the page.
if (Request["__EVENTTARGET"] == "btnUpdatePage")
{
UpdateStatus();
}
If the post back event target matches the assigned event target from the __doPostBack method, then I called a method to update the status.
This way I could avoid the issue. But I do not know why the event was not fired using the old ButtonClick function.
If the code works fine on your PC, the only thing that looks fishy to me are these 2 lines:
1. document.getElementById('ctl00_ContentPlaceHolder1_btnUpdateStatus');
2. btnUpdateStatus.setAttribute("onclick", "");
For the first line , you should be doing this, instead:
document.getElementById('<%=btnUpdateStatus.ClientID%>');
And for the second line, it seems that you are setting the onclick handler to "" which basically shouldn't do anything.
It may not be the problem at all. The best thing to do is debug it with Firebug, putting a breakpoint in the appropriate Javascript functions that are being called.

'onbeforeunload' Fires Twice

I want to send an ajax request when a user leaves a page or closes the window.
Here is my code inside :
<script type="text/javascript">
function sendajax(){
$.ajax({
url: "someurl",
data: mydata,
async : false
});
}
</script>
<script type="text/javascript">
window.onbeforeunload=function(){sendajax();};
</script>
When the event occurs the event fires twice.
Why does in happen?
I know I can prevent it by adding a variable var ajaxSent=true; but may be there is a cleaner way to do it?
UPD:
I replaced the sendajax function content with some other code (without sending ajax) and found out that ajax is not the one causing the problem. It still enters the function twice.
Based on the code in your edit and comments, it looks like it could simply be caused by the broken link you are clicking to leave the page.
Given the following code:
<script>
function doSomething() { console.log('onbeforeunload fired'); }
window.onbeforeunload = doSomething;
</script>
link A
link B
If I click on link A, I get two console log entries, if I click on link B I only get one.
It looks like it could be a quirk of how the browsers handle their internal "This web page has not been found" pages, causing your page to be refreshed and closed again before showing the message, leaving you with two occurrences of the onbeforeunload event.
I had the same problem and it took a while to understand and resolve, sharing the case details:
There was a custom JS within our template that manipulated the menu.
It caused the unload to fire twice, only when clicking on the menu links, not on other links, and only in IE/EDGE.
We eventually stopped the propagation on these links and the problem was resolved.
$('.SELECTOR a[href^="http://"]').on('click', function(e){
e.stopPropagation();
});
It's a specific bug in your application, therefore you won't find too much information on google.
You could try the following code:
<script type="text/javascript"><br>
window.onbeforeunload=function sendajax(){<br>
$.ajax({<br>
url: "someurl",<br>
data: mydata,<br>
async : false<br>
});<br>
};<br>
</script>
or you can define sendajax() {} at some place and the use it like onbeforeunload = "sendajax()" not as onbeforeunload = "function () { sendajax() }"
beforeUnload is cancellable
I know this post is quite old but from the Chrome Pagelifecycle API documentation, browsers can occasionally partially unload pages to save resources. https://developers.google.com/web/updates/2018/07/page-lifecycle-api beforeUnload is not reliable to make sure that the page is closed. This especially happens on android devices when the screen is locked.
There is a jsfiddle that I found somebody wrote that you can test out https://jsfiddle.net/ov6b9pdL/. Keep the screen locked for 5-10 minutes on Chrome android and you'll see that beforeUnload is fired without even closing the tab.
$(document).ready(function() {
window.addEventListener('beforeunload', showLoader);
});
var showLoader = function() {
$('#loader').show();
};
Agree with AlonMichaeli's concept.
In my application there was anchor tag wrapped with in a div together with couple of spans. When Anchor was clicked on a dirty page, there was couple of 'Leave site' notifications.
It worked fine if any other part of menuItem (div or spans) are clicked.
So in custom javascript method I've added stopped propagation and preventDefault only if anchor tag is clicked. Somehow in this case preventDefault is necessary.
function menuItemClicked(event: JQueryEventObject) {
var item = $(event.target);
if (item.is(".anchor-item")) {
event.stopPropagation();
event.preventDefault();
}
href = item.closest(".anchor-item").attr("href");
if (!event.ctrlKey && href) {
window.location.href = href;
}
}

Categories

Resources