I'm new to creating JavaScript bookmarklets but have got a certain way in solving my problems but have got stuck on one final bit.
Basically, I want to create a bookmarklet that will replace text in 2 places in the URL - the subdomain and the URI.
I have managed to do this for the first part:
(function() {
window.location = window.location
.toString()
.replace(/^https:\/\/www\./, "https://edit.");
})();
Next, I need to grab some metadata (cab-id) from the page. I've managed to do this an print it to the console:
function getCabID() {
var metas = document.getElementsByTagName("meta");
for (var i = 0; i < metas.length; i++) {
if (metas[i].getAttribute("name") == "cab-id") {
return metas[i].getAttribute("content");
}
}
return "";
}
console.log(getCabID());
The next thing I need to do is replace the end of the url (everything from "www.xxxxxx.org.uk/*" with the following:
/EPiServer/CMS/Home#context=epi.cms.contentdata:///
I can't figure out how to do this, I'm really struggling. I've come up with the following but it's not working:
(function() {
var url=window.location.href;
stringUrl=String(url);
stringUrl=stringUrl.replace(/^https:\/\/www.xxxxxx.org.uk\/, "https://edit.xxxxxx.org.uk/EPiServer/CMS/Home#context=epi.cms.contentdata:///");
document.location=stringUrl;
})();
I'll also need to pop the cab-id at the end of all this directly after ///.
Sorry for the long question but what I need to do is:
Make the 3rd one actually work!
Combine the 3 functions
Any tips would be massively appreciated :D
As I understood your question, the following bookmarklet probably allows to combine the 2nd and 3rd steps:
javascript:(function() {
window.location.href = "https://edit.xxxxxx.org.uk/EPiServer/CMS/Home#context=epi.cms.contentdata:///" + getCabID();
function getCabID() {
var metas = document.getElementsByTagName("meta");
for (var i = 0; i < metas.length; i++) {
if (metas[i].getAttribute("name") == "cab-id") {
return metas[i].getAttribute("content");
}
}
return "";
}
})();
Related
I want to write a script to resolve double redirects automatically after a page move. Here is what I have started with:
(function () {
var api = new mw.Api();
api.get( {
action: 'query',
list: 'backlinks',
blpageid: mw.config.get('wgArticleId'),
blfilterredir: 'redirects',
blredirect: true,
bllimit: 500
} ).done( function (data) {
var fixed = 0;
redirects = data.query.backlinks;
for (var i=0; i<redirects.length; i++) {
var doubles = redirects[i].redirlinks;
if (doubles === undefined) {
continue;
}
for (var j=0; j<doubles.length; j++) {
console.log(doubles[j]);
fixed ++;
}
}
mw.notify(fixed);
} );
})();
The problem is that if I run this function on a page like Wikipedia:Blocking policy the script returns some pages that are not actually double-redirects, but merely redirects containing links to it.
I can check each of them to see where they are actually pointing to, but isn't there any better way? i.e. a simple method to retrieve double redirects only.
If you are happy with using python and the pywikibot framework there is https://m.mediawiki.org/wiki/Manual:Pywikibot/redirect.py which should do what you want.
Otherwise you might want to work with the output of Special:DoubleRedirects.
Here's my code:
if(typeof(Storage)!==undefined) {
// Web storage support
if(localStorage.hashes != "") {
var hashes = jQuery.parseJSON(localStorage.hashes);
for (var i = 0; i < hashes.length; i++) {
// Do stuff here
}
}
else {
var hashes = [];
}
}
else {
// No web storage support
}
I don't really know what's going on, but when I try to load the page with this code from a device for the first time, the rest of my code doesn't work the way it should. However, if I comment it out then visit the page for the first time everything works. I can then uncomment it, reload the page, and everything will continue to work. This is really the best I can describe what's happening.
I believe you could have done a little more debugging before posting this.
Have you tried logging/ adding checks (to see where exactly this issue is coming from and what the error is) ?
But since we're here, here are my tips for localStorage :
Use modernizr (http://modernizr.com/)
if(Modernizr.localstorage){ /* Your code */}
Make some generic get and set functions
function get(key) {
if(Modernizr.localstorage) {
if(localStorage[key] != null) {
return localStorage[key];
}
}
return null;
}
function set(key, value) {
if(Modernizr.localstorage) {
localStorage[key] = value;
}
return null;
}
This is pretty rough, you tweek it to make it safer and respond to your needs
Put try/catch inside your get and set functions, you don't want write operations to impact your program
I figured it out! So in the above code I check if they had localStorage available, and if they do, I just assume that they have some hashes stored in there. This obviously creates a problem on their first visit as they wouldn't have any hashes saved yet. So I have to check if they have any, if they do, then do the for loop, otherwise just set it to an empty array. Like so!
if(typeof(Storage) !== "undefined") {
// Web storage support
if(localStorage.hashes != "") {
hashes = JSON.parse(localStorage.getItem("hashes"));
if(hashes) {
for (var i = 0; i < hashes.length; i++) {
// Do Stuff
}
} else {
hashes = [];
}
}
else {
hashes = [];
}
}
else {
// No web storage support
hashes = [];
}
Thanks to jbabey for tips on cleaning up my code some!
I have a code that has no syntax errors (Dreamweaver) but the Chrome JS console is saying that ExistsCookie is undefined. The cookie was in the cookie list for that site but the page is not redirecting. What am I doing wrong? NOTE: I know people can turn cookies off.
var cname = "voicevote"
var data ="1";
function CheckForCookie()
{
if( ExistsCookie(cname) )
{
window.location.replace("cookie.htm")
}
}
Most likely, ExistsCookie is a function that you haven't included in your script- if this was taken from a tutorial on some other website, look there- there may be a function on that page which you forgot to include in your code.
EDIT: After some googling, it looks like this is what you need:
function ExistsCookie(name)
{
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
var aCrumb = aCookie[i].split("=");
if (name == aCrumb[0])
return true;
}
return false;
}
(Source, which appears to match original question)
yeah, so can i do that?
i have a program already written that has two functions.. and one is recursive..
so i want to know how can i execute just one line of code at a time by pressing a button..
i hope it's possible
and also i'm doing this in a web page
this is my script.. it has no importance but just for you to make an idea..
READ THIS... i don't want to debug it with firebug or whatever... i want to make this myself inside my program... i want to make the code execute 1 line at a time when i press a button..so basically im building my own debugger.. the graphical part is already done.. i only need to know how to do this..
function nod(){
var info;
var st;
var dr;
}
function help(){
var rad;
}
var h = new help();
h.rad = new nod();
h.rad = null;
function create(h,x)
{
if(h.rad==null)
{
h.rad = new nod();
h.rad.info = x ;
h.rad.st = h.rad.dr = null;
}
else{
if(x < h.rad.info){
var h1;
h1 = new help();
h1.rad = h.rad.st;
create(h1,x);
h.rad.st = h1.rad;
}
else{
var h2;
h2 = new help();
h2.rad = h.rad.dr;
create(h2,x);
h.rad.dr = h2.rad;
}
}
}
function read(h)
{
var input = [0,10,2,1,8,9,4,5,3,6,20,11,30,21,31,22,23,
];
var i;
for(i=1;i<=16;i++)
{
create(h,input[i]);
}
}
read(h);
Open your site in Chrome and use the integrated script debugger to execute the script step by step after a breakpoint you set.
But have at least a quick look at the whole box of tools I linked too to ensure you know what you can expect and use the best tool for your need.
I have a javascript on my server, and i need to set a value / calling a function inside the javascript when calling a URL. Is there anyway of doing that ?
UPDATE:
<script type="application/x-javascript" src="test-test.js"></script>
Thats how it its loaded on the HTML site. And I want to call the function test(e,e) inside test-test.js, by putting in the URL in a browser with some values for e,e..
Unless you are using one of the few web servers that employs server-side JavaScript, your script is going to run in the browser after the page is loaded. If you want to include information from the URL in your script (and this assumes that you can use a query string without changing the server's behavior), you can use window.location.search to get everything from the question mark onwards.
This function will return either the entire query string (without the question mark) or a semicolon-delimited list of values matching the name value you feed it:
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
So if the URL was, say:
http://www.yoursite.com/somepage.html?name=John%20Doe&occupation=layabout
if you call getUrlQueryString() you would get back name=John Doe&occupation=layabout. If you call getUrlQueryString("name"), you would get back John Doe.
(And yes, I like banner-style indents. So sue me.)
You can use address plugin to be able to pass some condition in urls trough # symbol: http://my_site/my_page#your_condition
in the html you can write something like this:
<script>
$(function(){
// Init and change handlers
$.address.init().change(function(event) {
if (event.value == "your_condition")
run_my_finction();
});
)};
<script>
See this exaple for the futher help.
If you want to execute JavaScript from the browsers' address bar, you can use a self-invoking function:
javascript:(function () {
alert('Hello World');
/* Call the JavaScript functions you require */
})();