Keep the console script persistent in Google Chrome - javascript

I have a script I want to use in the Google Chrome console. But this script is going to reload the page. A bit like this :
setInterval(function(){location.reload();},3000);
The problem is, once it's reloaded, the script stops and the console is cleared. I tried the option "Preserve log on navigation" : it preserves the log, but the script doesn't restart after reloading.
How should I do ? Thanks :)

There is no way to actually do that. The only possible way I found is to develop a Chrome' extension and place your script on it. Your script will be excecuted every time the target page is loaded, so when you execute the location.refresh() method , the next time the page is loaded your script will be executed all again and so on. If you wish to persist some data between page loads, then you can use localStorage.
Find more information here https://developer.chrome.com/extensions/getstarted
How to inject scripts via extensions ?: https://developer.chrome.com/extensions/content_scriptsremember that the scope of the extensions is isolated from the rest of the page, so you cant directly access JS variables or functions declared in the page itself from an extension BUT you can interact with the DOM. Good luck

I am using a cool Chrome Extension called Resource Override, which allows you to inject a script on specific urls. So all you have to do is put your url (with * on each end), and create a JS file injected into the HEAD, and it will be ran every time. You start from scratch on every page though, so I'm not sure how you can persist data. Maybe in cookies?

Try creating a parent html document that has an iframe whose source is the original html page. Place the javascript in the parent html page and tell it to reload the iframe.

Related

Can a javascript code continue running throughout different web pages?

I am trying to code a javascript that runs throughout different web pages. The script should type something into a search bar, click search, click a result, then save each result text into an array. It looks something like:
function returnresults(queries){
arrayofcontent = [];
for each query {
type query in searchbar;
submit search;
result[0].click(); // go to first result
arrayofcontent.push(pagecontent.innertext);
}
return arrayofcontent;
}
The issue is that the script seems to be stopping after the script clicks search, which makes me think that the script is unloading itself when moving to another page, even though I'm typing the script directly into the javascript console in Google Chrome. Does anyone know how to tell Google Chrome to keep running the script even after moving between pages?
Short answer: No.
When you examine what's happening in a browser tab (including working with the console), you are only able to inspect what's loaded in that tab. If you navigate to another page in that tab, everything that was in memory from the last page is thrown out and the new page content is loaded.
What you need is to store the state of the script and then retrieve that state on the other page. Storing state can be done in many different ways (cookies, localStorage, sessionStorage, server-side databases) and you'll need to decide which is right for your architecture and use case.
if you want to inject your script to different web pages you can do that by developing a chrome extension . A extension enables to inject your script depending on your logic
here is the link to get started
https://developer.chrome.com/extensions/getstarted

Loading external javascript in a bookmarklet via a script loader

Here is my current setup:
I have a script on our Sharepoint.
Each user adds this in a bookmarklet to use it.
If I make an update, they have to go and set up the bookmark all over again.
What I want to do:
User adds script loader to bookmark toolbar
They click it, and it loads the script from our Sharepoint.
This way, if I need to make any changes, they don't have to do anything and changes will be reflected automatically.
My bookmarklets/scripts depend on jQuery to make ajax quests and just for general ease of use.
I am currently using this: http://benalman.com/projects/run-jquery-code-bookmarklet/
Is there a framework that I can use for this kind of thing? I know Visual Event uses a loader, but since it was compressed with Closure, I can't really tell what it's doing. I understand that since things are loaded asynchronously in Javascript, I would have to wrap all my code inside of jquery being loaded, which is fine.. I just need a way to do it.
all you need to do is move your bookmarklet code to an external js file, and then inject that file using a bookmarklet. That way, the bookmarklet injects the latest logic, and you don't have to ever re-bookmark again.
in that external script, you can paste the jQuery.js file's contents above your JS code to make sure it runs as expected.
modify the url to point to your script:
javascript:(function (){document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src='http://domain.com/scripts/external.js?'+Math.random();}());
if your intranet has decent caching setup, you can remove the "+Math.random()" part, but on an intranet, performance is rarely a problem for on-demand single-url asset loading, the the random url ensure everyone always gets the latest copy.

How does a browser include a javascript file?

When you add a script tag with an src field pointing to a javascript file, the browser gets it and executes it.
What I am wondering is how does this process work. Does the file get fetched and then somehow eval()'ed? Is it a mystical process that happens outside of the scope we have access? Or can we monitor/interfere this?
To explain what I want to achieve:
I want to give access to third parties to customize their page on my site by linking to their own javascript files. I want to be able to centrally log any errors that prevent those external scripts from loading (i.e. their server is down, parsing errors, whatever). Is it possible?
Thanks!
Obviously there are other ways to solve this such as hosting their scripts on my server and giving them a way to update them, but I 'm interested in knowing if my current approach is possible.
You can look at specific implementation in Firefox & Chromium sources with some grep magic, for your specific scenario I'd asynchronously subload those by inserting script tags on the fly and listening to global errors/events (eg window.onerror) from there.
It loads the java script file while loading the page and stores that script in its cache. If you load page another time then it will get that js from the cache.

Force refresh doesn't work for Head JS

When scripts are loaded via Head JS I am unable to force the content to refresh using the Ctrl+F5 (or equivalent) keyboard shortcut.
The scripts cache correctly and the browser obeys the cache directives sent from the server (I'm using IIS 7.5). But unlike scripts tags included directly in the markup, I can't override the cache and force a refresh of the scripts loaded via Head JS.
I'm assuming this is a consequence of the way the scripts are loaded dynamically. I can live with this behaviour because forcing the refresh is only convenient during development, and I know of other ways I can force the content to be retrieved from the server.
I just wondered if anyone could explain why this is the case...
Update
This was never a problem for us in Live, because the cache directives for our static content were set appropriately. It was only ever a problem in Development and QA, The options left available to me were...
Configure all Dev and QA browsers to never cache content.
Configure the static content cache directives differently for Dev and QA environments - essentially setting MaxAge to something so small the content would always be expired. Only setting the correct MaxAge value in Live.
I went with the second option.
Dynamic script loading is not a part of the page loading proper. When you force refresh, the browser reloads the page and all resources referenced in its HTML and in referenced CSS files, but the scripts you load with head.js are not referenced in the page content and the browser has no way to figure out that head.js is going to create references to additional resources. At the point where these references are created, the browser is no longer refreshing the page and thus normal cache rules apply.
You can force reload of your scripts by appending unique query strings to their URLs (e.g. jquery.js?random=437593486394), but this will disable caching for all loads of your page, not just when you force refresh.
This is also a problem with require.js. Hopefully one of these work arounds will also apply to Head.Js
If using Chrome, open the developer tools panel on the Network tab, right click and choose 'Clear Browser Cache'
Do a bit of 'Cache-busting' by appending a datetime stamp to the query string for js resources
If your using IIS (which it looks like you are). Go to the HTTP Response Headers panel of your website, click Set Common Headers and set Expire Web content to immediately.
The latter is my preferred option for my development machine
I wouldn't say its a question of dynamic or not dynamic, when you inject a script it still causes the browser to make a HTTP request and apply whatever caching logic it applies.
Like mentioned above if you don't want scripts to be cached ..dynamic or static, it doesn't matter, you will usually have to append a timestamp in the form of a query string to it.
If you just want to see if you changes are working, do a force refresh in your browser ...usually CTRL+F5

How to change content after page is loaded (JS)?

I would like a javascript to run after a page is loaded , like on the example below with a delay of 6seconds. Right after the page loads the rest of JS is lost (obvious)...
Got any ideea how change content after page is loaded without clicking a button?
javascript:window.location = "http://example.com";
setTimeout(function() {
document.getElementById('lightbox').style.display = 'none';
}, 6000);
Once you set window.location the original page will be unloaded before the new page is loaded by the browser. This means your script will be gone before the new page start loading and thus can't modify the new HTML anymore.
This behavior is inherent to the security model of the browser. Without it you could inject any JavaScript into any web site of your choosing, which would be a huge security risk. What you are asking for is so-called XSS (for cross site scripting), which is prevented by the browser applying a so-called SOP (for same-original policy).
There are some common ways to work around this limitation in a safe way:
Set up a proxy to serve both your JavaScript and the original site. This way both your script and the original site come from the same domain and satisfy the browser's same-original policy (SOP). You could run the original site in an iframe with your custom script occupying the top-level window. Alternatively you could inject your script into the HTML as it is being retrieved through your proxy.
Run your script as a browser add-on or user-script. If you choose to do this, the user will have to specifically grant your script the rights to run locally with elevated rights. Greasemonkey popularized client-side scripts for Firefox a few years ago, but recently they seem to have lost momentum.
Ask the site owner to include your script. I doubt this is a valid option for your situation. But if it is a valid option it is definitely the simplest one.
Ask the user to run your script after the site has loaded. This one is probably also not valid for you, but if valid it would once again be a very simple solution.
Your example shows that you are first redirecting and then attempting to hide #lightbox. This script would not work, because you are redirecting the browser to another site before #lightbox gets hidden.
In short, you cannot have Javascript of a previous page manipulate DOM of the next page if you redirect the user to another URL (or even the same URL). Only Javascript that is 'on currently open page' can manipulate currently open page and no other pages.
I have not understood what you are saying. JS is lost? Please be more clear.
I think what you are talking about is the jquery ready function which runs after the DOM is ready. Or in the other case, try using window.onload() function.
This should do the job:
$(window).bind('load', function() {
// your code here
});
Then simply add the delay to your added code with .delay("6000");
The inserted code will only run when your page is completely loaded.

Categories

Resources