Cannot use setTimout doesn't work in bookmarklet - javascript

Can I not use setTimeout() in a bookmark?
This works:
javascript:
document.location="mysite.com";
alert("test");
void(s);
This does not:
javascript:
document.location="mysite.com";
var t=setTimeout(function () {
alert("test");
}, 10000);
void(s);
Why is this?

Each time you change a page the entire javascript context is destroyed and recreated(This for security reasons and the fact that a context hell would be made)
document.location="mysite.com";
efectively changes the context of the page destroying any javascript reference left(in your case the timeout). The moment the new page has started loading your page has a new context.
for your timeout to work you would need a server that takes more than 10 seconds to respond(based on your second argument 10000 or to reduce the timeout to something like 10 ms).
document.location="mysite.com";
var t=setTimeout(function () { alert("test"); }, 10);
why would you need this?

Bookmarklets can do no more than what normal embedded script on a web page can do. If you can't do it with normal JavaScript, you can't do it with a bookmarklet.
In your example, if run as normal javascript embedded in the page, as soon as the page reloads the timeout would be gone, along with all other variables from that page. (Don't be mislead by the fact that JavaScript embedded in script tags will be re-run as the page is loaded. That would create a new timeout, but the previous one would be deleted.)
A more precise test would be to put your bookmarklet code into an a hyperlink on the page and click it (test). That is exactly the same as clicking a bookmark containing the same code. What you cannot do with this, you cannot do with a bookmarklet.
SOLUTIONS TO YOUR PROBLEM:
Option 1: Bookmarklet creates an iframe inside the current page, and continuously reloads the desired page inside that iframe.
Option 2: Bookmarklet opens a small window and inject javascript into it which continuously reloads the opener window.

Related

I want to refresh the page with location.reload () and then call the function but the function only executes for a moment and disappears

Here are the code I am using to call the function:
btn.addEventListener("click", () => {
myCalc();
location.reload()
})
The execution of the script is tied to the page. If a new page is loaded (even if it is the same one), the script being executed stops. It's like having a plan "I'll detonate this nuclear bomb in my kitchen, then make breakfast". No, you won't, that's not how nuclear bombs work, and that's not how location.reload() works ;)
What you can do instead is make sure that there is a script being run at the page load, that responds to certain state you have saved; so that even though your previous script died, the newly loaded script knows what to do next. The easiest way to do so is likely by using localStorage. Or, better yet, you can build your application in such a way that a reload is not necessary: this is called a Single-Page Application (SPA).

Get a bookmark to load a page and run javascript on it [duplicate]

I have a bookmark that opens my a google calendar page (http://www.google.com/calendar/renderOnline) and a bookmarklet that applies some javascript on it:
javascript:document.getElementById('gadgetcell').setAttribute('style','width:300px');document.getElementsByClassName('sn-frame')[0].setAttribute('style','width:300px');
Is there a way to combine these into a single bookmarklet so that i don't have to click twice all the time?
Thank you!
No. A bookmarklet runs in the context of the original page, so it can't change pages and keep running. You may find GreaseMonkey helpful if you always want to run that code on the page. Or, Stylish lets you apply user styles to pages.
You could use an extension to get the same behavior.
For example in Safari you would create a button that launches the URL and an injected script that runs your bookmarklet. GreaseMonkey and many other extensions frameworks can do similar things.
I had the thought to use a bookmarklet to do this:
javascript:location.href='http://google.com';setTimeout(function(){alert('hi');},2000);
The setTimeout function could be anything, and due to the 2 second timer, the page would have time to load and the arbitrary code would execute against it. But it didn't work. No matter what function I seem to try to call in the setTimeout, it just never executes, or perhaps it executes in some other space that was being destroyed as the new page loaded or something like that. That setTimeout code works fine as a bookmarklet as long as there's no location.href change, it seems.
However I wonder if perhaps a better approach would be to do an AJAX load of the page you want into the current space, and then try to execute something. If I get around to trying that I'll update here.

Chrome extension: page loads faster than extension code

I am working on the extension that needs to update page texts after page is loaded. I use window.onload in "content_script".
As I need to test my changes a lot I decided to create a little page with a few paragraphs of text and put it in my web server. But when this page loads - extension's window.onload doesn't trigger, wheres on any other internet page it works properly.
I started investigation and found out, that this is because of the page loading speed. So basically page loads faster than extension code.
It was verified by adding background image on the body linked to the external site. Like this:
body
{
background: url(http://colourunity.com/img/2013/07/autumn-wallpaper-computer-14172-hd-widescreen-wallpapers.jpg) no-repeat;
}
So the page's loading speed slows down and extension has enough time to load in and window.onload triggers.
Of course I don't worry about extension work, because it is too rare case when page loads that fast.
But still - is there anyway to bypass this?
Thanks.
The window object of your content script is not the same as the one of your page. From the content script documentation:
It's worth noting what happens with JavaScript objects that are shared by the page and the extension - for example, the window.onload event. Each isolated world sees its own version of the object.
Therefore listening for this event in your content script won't work as you intent, since it's not the one you want.
It doesn't matter anyway: you can specify at which point your script is executed via the run_at option. For example, if you choose to run it at document_idle, then you're guaranteed it's executed after the window.onload event of your page.
In other words, you can simply stop using the window.onload event, and directly run the code you need.

Refresh a page automatically from the Browser console

Good Day
I have never really used the browser console before, so I don't really know what it is capable of doing - What I want to achieve is the following:
How do I force/initiate an automatic refresh on a page from the browser console? That is, instead of having to press F5 everytime?
Also, does the console take jquery? Or does it depend on whether the web page you are on uses jquery or not?
Thank you!
Use a browser tab "A" to open and control another browser tab "B". This allows you to continuously auto-reload a Web page in tab "B" that otherwise you have no control over. Your reload command from tab "A" will not be wiped out when tab "B" is reloaded.
I use this to refresh a Website so that it does not time out and log me out. This approach does not require jQuery, and does not require you to have any control over the target Web page HTML code.
Open a browser new tab "A", press F12, select Console. Type in something like this:
win1 = window.open("https://www.example.com");
timer1 = setInterval(function(){win1.location.href="https://www.example.com"},10*60*1000);
The "win1" is to assign a Javascript variable name to the new browser tab "B", so that you can have Javascript control over it. The "timer1" is also to assign a variable name for good practice and for later control. The setInterVal function runs an anonymous function to call "win1" or tab "B" to refresh it's "location.href", every 10 minutes.
You'll probably have to keep both tabs open. "Pin" them for easy access. Close both tabs to stop the auto-reload. Hard refresh of tab "A" may also stop the auto reload. You might also be able to use the variable "timer1" to cancel the auto reload.
You can refresh a page from within the browser console by running the following command:
location.reload()
If the website you are on has jQuery loaded you will be able to run jQuery commands.
If the website does not have jQuery loaded you can use the following bookmark to inject jQuery into the page:
javascript:(function(e,a,g,h,f,c,b,d){if(!(f=e.jQuery)||g>f.fn.jquery||h(f)){c=a.createElement("script");c.type="text/javascript";c.src="http://ajax.googleapis.com/ajax/libs/jquery/"+g+"/jquery.min.js";c.onload=c.onreadystatechange=function(){if(!b&&(!(d=this.readyState)||d=="loaded"||d=="complete")){h((f=e.jQuery).noConflict(1),b=1);f(c).remove()}};a.documentElement.childNodes[0].appendChild(c)}})(window,document,"1.3.2",function($,L){(function(){var d=document.createElement("div"),c=document.getElementsByTagName("body")[0],e=false,g="";d.style.position="fixed";d.style.height="32px";d.style.width="220px";d.style.marginLeft="-110px";d.style.top="0";d.style.left="50%";d.style.padding="5px 10px";d.style.zIndex=1001;d.style.fontSize="12px";d.style.color="#222";d.style.backgroundColor="#f99";if(typeof jQuery!="undefined"){g="This page already using jQuery v"+jQuery.fn.jquery;return f()}else{if(typeof $=="function"){e=true}}function a(i,k){var h=document.createElement("script");h.src=i;var j=document.getElementsByTagName("head")[0],b=false;h.onload=h.onreadystatechange=function(){if(!b&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){b=true;k();h.onload=h.onreadystatechange=null;j.removeChild(h)}};j.appendChild(h)}a("http://code.jquery.com/jquery.min.js",function(){if(typeof jQuery=="undefined"){g="Sorry, but jQuery wasn't able to load"}else{g="This page is now jQuerified with v"+jQuery.fn.jquery;if(e){g+=" and noConflict(). Use $jq(), not $()."}}return f()});function f(){d.innerHTML=g;c.appendChild(d);window.setTimeout(function(){if(typeof jQuery=="undefined"){c.removeChild(d)}else{jQuery(d).fadeOut("slow",function(){jQuery(this).remove()});if(e){$jq=jQuery.noConflict()}}},2500)}})();});
If you want to use the console just type document.location.reload() in the console. But if you want to make it automatically - it needs to be in your code.
And yes, the console will take jquery if you have included the library in your code.
One more thing: for automatic refresh you need something like
setInterval(function(){ document.location.reload() },10*60*1000);
But it not gonna work in the console, because after the first refresh this code won't be in the console anymore. Just place it in your code.
You can use like
document.location.reload()
If your webpage includes jQuery. then jQuery will be avaliable in the console:)
To refresh you can type directly in console:
window.location.reload()
The simplest way is to you use a plugin.
"Super auto refresh" for example. Available for most of the browsers
Adding to #saeng's answer, in case you need to stop the interval after a certain period of time.
Open the console and write the below-mentioned snippet.
INTERVAL = 5 // seconds
STOP_AFTER = 15 // seconds
// Open the same link in the new tab
win1 = window.open(location.href);
// At every 5 seconds, reload the page
timer1 = setInterval(() => {
win1.location.reload();
console.log("Refreshed");
},INTERVAL*1000)
// Stop reloading after 15 seconds
setTimeout(() => clearInterval(timer1), STOP_AFTER*1000)
It will open a new tab with the same link and reload it at some interval. After a certain period of time, it will stop reloading.
Add this javascript
setTimeout(function () { location.reload(1); }, 5000);
Add this below meta tag to your page
<meta http-equiv="refresh" content="5; URL=http://mywebsite/mypage.aspx">
Many Thanks
ann

Load a page and apply javascript in a single bookmark

I have a bookmark that opens my a google calendar page (http://www.google.com/calendar/renderOnline) and a bookmarklet that applies some javascript on it:
javascript:document.getElementById('gadgetcell').setAttribute('style','width:300px');document.getElementsByClassName('sn-frame')[0].setAttribute('style','width:300px');
Is there a way to combine these into a single bookmarklet so that i don't have to click twice all the time?
Thank you!
No. A bookmarklet runs in the context of the original page, so it can't change pages and keep running. You may find GreaseMonkey helpful if you always want to run that code on the page. Or, Stylish lets you apply user styles to pages.
You could use an extension to get the same behavior.
For example in Safari you would create a button that launches the URL and an injected script that runs your bookmarklet. GreaseMonkey and many other extensions frameworks can do similar things.
I had the thought to use a bookmarklet to do this:
javascript:location.href='http://google.com';setTimeout(function(){alert('hi');},2000);
The setTimeout function could be anything, and due to the 2 second timer, the page would have time to load and the arbitrary code would execute against it. But it didn't work. No matter what function I seem to try to call in the setTimeout, it just never executes, or perhaps it executes in some other space that was being destroyed as the new page loaded or something like that. That setTimeout code works fine as a bookmarklet as long as there's no location.href change, it seems.
However I wonder if perhaps a better approach would be to do an AJAX load of the page you want into the current space, and then try to execute something. If I get around to trying that I'll update here.

Categories

Resources