Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, June 28, 2023

Web Design: Make Duplicate Forms And Remove/Reset Them

 I don't know if anyone else would ever need or want something like this, but here we go. If you want to be able to create multiple forms on demand on the same page along with maintaining the ability to remove them or interact with them, then this is for you. First thing first, we need to make an HTML document.

<!DOCTYPE html>

<html>

<head>

<title>Some Stupid Form Thing</title>

Now let's get our Javascript on! I know I add some stuff that is not needed, but I'm weird.

<script type="application/javascript">//<[CDATA[

"use strict";

//I like to do a global storage object

var storage = {

    "formdata": "",

    "fid": 1

}

// function to store original form setup

function getformdata() {

    storage["formdata"] = document.getElementById("form0").innerHTML;

}

//Creating new forms

function addform() {

    var newform = document.createElement("form");

    newform.id = "form" + storage["fid"]++;

    newform.innerHTML = storage["formdata"];

    document.getElementById("formlist").append(newform);

}

// Removing forms, or reset the last form

function removeform(b) {

    b.parentElement.remove();

    if (document.getElementById("formlist").children.length < 1) {

        storage["fid"] = 0;

        addform();

    }

}

//]]></script>

</head>

Now that all the delicious code is out of the way, we need to create the body that this will interact with. It's actually fairly simple.

<body onload="getformdata()">

<div id="formlist">

<form id="form0" action="#">

Employee ID: <input type="text" value="" class="eid" /><button type="button">Do a thing</button><br />

<button type="button" onclick="removeform(this)">Remove</button>

/form>

</div>

<button onclick="addform()">Add Form</button>

</body>

</html>

Summary time. I am using a div as a container to create and remove forms in. Using the DOM we can isolate what we need inside of whatever container and use that to modify whatever with minimal navigation, no extra overhead of frameworks needed. I don't know why anyone would need this, other than the reason I made it that I'm not going to say. But there you go.

Thursday, April 6, 2023

Web Design: Copy To Clipboard with an SVG Graphic!

 Been a long time since I've had time to post. Now, let's get into the meat of this. It's easy enough to copy to a clipboard in Javascript. I did that. Let's also talk using a graphical icon to make it not look like garbage. The Javascript code to copy to a clipboard looks something simple like this:


navigator.clipboard.writeText(document.getElementById("elementwithvalue").value);


Easy enough. Now, let's talk a dead simple icon that takes up little to no room and is easy enough to copy and alter.


<svg width="20px" height="20px">

<rect x="3" y="3" height="12px" width="12px" rx="3" ry="3" style="stroke-width:1;stroke:black;fill:white"/>

<rect x="7" y="7" height="12px" width="12px" rx="3" ry="3" style="stroke-width:1;stroke:black;fill:white"/>

</svg>


Easy enough, just a little black and white icon that looks close enough to the double paper thing to do a thing. All together it might look something like this:


<input type="text" id="kopimi">Something useful</input><button type="button" onclick="navigator.clipboard.writeText(document.getElementById('kopimi').value)" style="padding0;margin0"><svg width="20px" height="20px">

<rect x="3" y="3" height="12px" width="12px" rx="3" ry="3" style="stroke-width:1;stroke:black;fill:white"/>

<rect x="7" y="7" height="12px" width="12px" rx="3" ry="3" style="stroke-width:1;stroke:black;fill:white"/>

</svg></button>


And there you have it, a stupid little input box with a copy icon button. Enjoy, copy whatever.

Wednesday, February 27, 2013

Chrome CORS

This is a bit of a follow-up post to my Refused to set unsafe header post. A question I was asked was about how to do something with CORS in Chrome, and my immediate findings were that it is impossible. As of recently I looked back into it and have come across a couple possible solution.

The first possible solution is to make sure to send the proper headers, as Chrome will take into account what the server says is allowed. For this, you can set the access control headers however you want. For the example, I will show the php version I found.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");

This will allow you to set the various headers you would need for a CORS request. Another possibility is by using a content type that the control isn't strictly enforced. With that, it seems by setting the Content-Type to plain/text, it should go through without a problem.

I personally haven't tried either of these because I have yet to have a use for it with what I do, however I wanted to share this bit of information should anyone be curious and happen across here.

Tuesday, October 16, 2012

MyBB Post BBCode Button Problem

I wanted to post this a couple days ago when the problem was brought to my attention at a forum I code for, but was too busy to get it up until now. The problem has a fix for it, here. I just want to go over quickly what is the cause of the problem and let people know it may effect Chrome and Opera. The fix was simply changing some variable names, so it wasn't anything too complicated.

So Firefox implemented something called Microdata API. This is a new thing for HTML5 that adds more information to your markup. The catch is, whether or not you are using HTML5, it still effects your site. It adds new DOM attributes that MyBB 1.6.8 is using. This particular one is itemData. That is now an object and due to the way the script was made for the post editor, it just screws it up. From what I've read, Chrome and Opera will be implementing them soon. I hope eventually it will be made to only effect HTML5 pages.

I have yet to read up how to use the Microdata API, but if you are interested, you can find notes on it here.

Friday, July 27, 2012

Technical Speak (some thoughts and advice)

This post is not going to be technical so much as I really want to write about some tech things people say that are either completely wrong or just down right annoying. So take this how you will, but this is an opinion piece.

Something I once did before I knew much about computers but now that drives me crazy when I hear it, is when people talk about Java and call it Javascript or visa versa. Let us get a few things straight. Java is not related to Javascript nor the other way around. Javascript is a scripting language based on ECMAScript whereas Java is an interpreted language developed by Sun Microsystems. While Java can be used as a web technology, it is not the same as Javascript and while they have some similar naming conventions, any real depth into some code would reveal they are very dissimilar. So stop mixing them up, it is frustrating.

Another irritating point for me was created by the media, "Mac vs PC." The real goal of this is Mac OS vs Windows. Mac computers are PC's, as PC stands for personal computer. Furthermore, Mac computers can run Windows and if you're crafty, you can run a Mac OS on another PC, virtual machines being the easiest to get things going. Also some people throw Linux into the list. Well, OS X is Unix based as well. So they have some similar things to them. As to which is better, all three of them suck. It is just a matter of picking which one sucks less at what you personally need to accomplish. None of them are good at everything no matter what they claim.

Overuse of acronyms. In the technical world, many acronyms exist. Many acronyms overlap and it depends on what you are talking about. Overuse of acronyms in situations where it is not necessary is annoying and even a tech geek can get lost in such conversations. Granted there are exceptions where some technologies are explicitly referred to their acronym based name because some of the names are long and annoying. Some examples are XML (eXtensible Markup Language), HTML (HyperText Markup Language), or even php (Personal Home Page/Hypertext Preprocessor [it has changed over time]). Choosing to use all those acronyms in an environment outside of a situation that deals directly with such things is annoying, confusing and not many people can follow clearly. Use words.

Being able to navigate a website does not make you tech savvy, same goes for navigating software. I am relatively tech savvy and I get lost on so many websites and various user interfaces. One annoying example is of Microsoft Office. They keep changing the interface, and while I know what I want to do, I can spend a lot of time looking for various options. These things are esoteric and not standardized. While many try to keep similar conventions in an attempt to create better ease of use, they do not have to. Reliance on people trying to make similar and familiar interfaces is not possible.

Do not use tech terms you do not understand. If the media is to teach us anything, let it be this. For example the famous CIS line, "I'll make a GUI interface in visual basic, see if I can track an IP address" (GUI pronounced "gooey"). Taking this I would have to respond, okay, I will make an OS in Piet, see if I can make a super computer. Despite the lack of need to sum up why this is dumb, I am going to do it anyway. A GUI is not necessary for any of this. A good deal of tools for sniffing are done in command line interfaces because there is no point in the extra computational time and effort going to making a pretty window. Visual Basic is a dumb choice. I don't even know if you could make a sniffer from VB. If you can, it is probably some random .NET feature that is a waste of time. Now you do not "track" an ip, you can trace a route. Tracing would be following something along its path. That is a small thing to pick at, but tracking an ip would be like sniffing just that ip. Tracing would be finding the origin.

Using tech terms from one thing for a separate case.When drawing a comparison it is fine. However, using that comparison like the cases are equal is usually not fine.

Comparing things on levels that they are not comparable. I am sure at some point you have come across things like Perl vs Python, where they argue about dumb things like which is easier to read or application. Seeing as how Perl was more so made for text processing and Python is more of a general purpose language, they are obviously not going to be good at the same things. Benchmarking comparisons are one thing, but arguing about readability or which way of doing things is better is dumb because it depends on the application and the person.

Skids. Script kiddies. People that claim to hack when they are using premade tools without knowledge of the underlying innerworks of how or why things work they way they do. Downloading things like custom firmware to break a game system or opening up a tool to do some network scanning. Some of these can be dangerous if you do not have some understanding of how they work. In this light, the use is not that of a tool but a black box effect. Someone puts something in and gets the desired result out without understanding what just happened. So not everyone that uses these tools are skids or something to that effect, some actually understand in general how they work and use a premade tool to build something else faster.

So those are just some thoughts and opinions based off of things I have heard people said that just really catch me the wrong way and I have seen them criticized for saying such things as well. An easy way to keep yourself from saying something that will annoy others, whether you are right or wrong, is to remember you do not need to prove anything to anyone what you know, because you already know you know it.

Saturday, July 14, 2012

Flip a web page

I know there are a lot of people out there that like messing with others, so I got bored and decided to make a quick little bit of Javascript to do that. This will only work in browsers that support CSS3 and is a bit lengthy because certain browsers need their own special tags. So if you want to flip a page someone is browsing, or maybe even yourself, just enter this code in the address bar of the browser to flip a site:

javascript:document.body.setAttribute("style", "transform:rotate(180deg);-ms-transform:rotate(180deg);-moz-transform:rotate(180deg);-webkit-transform:rotate(180deg);-o-transform:rotate(180deg);");void(0);

It's as simple as that, the page should be flipped. Also, here's a link to do it, you can set it as a bookmark to make a bookmarklet: flip

Sunday, June 10, 2012

Refused to set unsafe header

*** If interested in CORS, try this.

This is an annoying little error that I've seen some people mention and even ran into with JavaScript. Moreover, it appears only in Webkit based browsers. So what's the problem? Basically a browser like Google Chrome will not change certain http headers in an XMLHttpRequest using setRequestHeader(). This is not a problem in Firefox or Opera from my testing so far. According to W3, it is actually the behavior they have as "standard" in their working draft. Headers they don't want you to overwrite are
"
  • Accept-Charset
  • Accept-Encoding
  • Access-Control-Request-Headers
  • Access-Control-Request-Method
  • Connection
  • Content-Length
  • Cookie
  • Cookie2
  • Date
  • DNT
  • Expect
  • Host
  • Keep-Alive
  • Origin
  • Referer
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • User-Agent
  • Via
Or if the start of header is a case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec-)."[1]
Now as to where this could be a problem, for me at least, is when I am trying to spoof some headers and want to do so in a browser as apposed to writing a script or getting an addon to do so for me. However, there is a security risk it could open up called HTTP Request Smuggling. As to how one would pull it off, I think an XSS vulnerability would need to be there as well for this in JavaScript to do anything. Bottom line for the security of it on the design end, make sure you check your sources before you use things like external scripts. As for user-end security, just be careful what sites you go to and use some common sense when you can.

Now as for ways around this, you would need either an addon to modify this for you or use related command line arguments. For example, to change the User-Agent header, you launch Chrome from your terminal with the option --user-agent="Some new UA string". As for an addon to do this, I do not know of any or if it is even possible, but if I find something I will update that here.

*[1] - http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

Wednesday, May 9, 2012

WebGL Firefox Error

So I figured I'd post about this, since I ran into a problem and had to dig through some forum posts to find how to fix this. My problem was on Ubuntu 10.04 LTS using Firefox 12.0, with NVIDIA GeForce Go 6150. Trying to use WebGL gave me the error that I forgot to save because I'm smart like that.

Anyway, the quick fix was to enter in your url about:config, then search for WebGL, then enable webgl.force-enabled. No idea if it will cause any problems, but for now it works.

***Edit:
Updated to Ubuntu 12.04 LTS, same settings and everything and now WebGL just refuses to work at all. No solution found yet, all the ones that I tried did absolutely nothing.

Monday, March 19, 2012

NoScript URL Javascript

I've been messing around with javascript and helping someone learn it, and one thing I've noticed is a lot of people seem to have NoScript now. NoScript is an addon that can allow you to selectively run or block javascript. While this is great, there is one option I don't see openly on the options for it. Whenever trying to run javascript in the url bar, it's blocked. While this is good for people dumb enough to run javascript directly from someone not trustworthy (I have used url run javascript to get someone's cookie information and hijack their session), it can be a problem when just messing around with stuff for someone who knows what they are doing but doesn't know about the way to allow url run javascript.

So to find the option, first go to the about:config (enter about:config in your url). Then in the filter, enter noscript.allowURLBarJS. You can right click and select the toggle option or simply double click the result you get. Once set to true, should be able to run url javascript, but only on sites that the domain is allowed to run javascript. Running javascript in the url still sandboxes it in to whatever tab you're on.

Whatever you do, be careful what you run when using this, can lead to information being taken to breaking some stuff. Other times, can be just a way to mess around with a site you're on quickly and easily, like bookmarklets.

Tuesday, January 24, 2012

IRC message Regex

So I'm in the process of making an irc bot, and one of the problems I always seem to have is parsing the message. If you don't know what parsing means, the simplest explanation is changing the message, in this case breaking it down into some form of an object that organizes the data for it.

Normally I would split it and then check various information from it being split then check all the split parameters and try to organize it, however when searching recently I found an easier way. Now keep in mind, this is client side parsing. I found the original on Caleb Delnay, so original credit goes here, but I wanted to expand upon it and convert it to work with the other subtle changes in regex across other languages.

*** There were further improvements added by someone else who I found thanks to some referrals in the stats thanks to a lovely accreditation to this post. Check out more info at mybuddymichael.com. I'll try to integrate the changes into my post once I can take some time to give it a good lookover and try it out a bit (hopefully it will help out with a new bot I'm currently working on in Haskell).

The original .NET compatible regex is
^(:(?<prefix>\S+) )?(?<command>\S+)( (?!:)(?<params>.+?))?( :(?<trail>.+))?$

Python (place in an r"" string so you won't need to escape backslashes), Perl, PHP, and AS3:
^(:(?P<prefix>\S+) )?(?P<command>\S+)( (?!:)(?P<params>.+?))?( :(?P<trail>.+))?$

Java (before 7 didn't support named groups, want to look at groups 2, 3, 5 and 7):
^(:(\\S+) )?(\\S+)( (?!:)(.+?))?( :(.+))?$

Java (7 and up supports named groups, have not tried this yet):
^(:(?<prefix>\\S+) )?(?<command>\\S+)( (?!:)(?<params>.+?))?( :(?<trail>.+))?$

JavaScript (no named grouping, use groups 2, 3, 5, and 7, does not need to be in a string):
/^(:(\S+) )?(\S+)( (?!:)(.+?))?( :(.+))?$/

The basic premise is under the assumption messages are formatted along the lines of :<prefix> <command> <params> :<trailing>, where any values are optional. If you know a better way to do any of them are know ways in languages I left out, let me know. As far as the regex methods and ways to work it out, that is up to you, I am just supplying the pattern and it is up to you so use it correctly.

Since regex can be complicated, hopefully this saves everyone some time, figuring out the needed methods to use it shouldn't be too hard.



***Edit:
After a comment about some stuff in the RFC, I played around with trying to make the regex work with that specification, I came up with a partially working version. Due to the complexity, my lack of knowledge and lack of benefit from this, I will only post the one edit I made and hopefully not bother with this again. While this is good for something quick and dirty, string methods seem to be more practical.

^(:(?P<prefix>\S+) )?(?P<command>\S+)( (?!:)(?P<params>\S{14} (:)?|.+ :?))?((?P<trail>.+))?$

The params section will end up with either a trailing space or a space and colon. That's the best I could do, and the last I'll do of this.

Wednesday, January 18, 2012

Javascript Ajax and keeping order

The title is about as descriptive as I could come up with for this, but allow me to elaborate. On a forum I code for, basically my coding is fixing and editing shit that's either broken or unsatisfactory, they decided to install a shoutbox. The shoutbox program worked with one major flaw. The Ajax requests for the shout were not being tracked and therefore jumping out of flow, which broke shit causing the script to shit itself and led to a bunch of problems down to my browser throwing an error with the socket, posts duplicating, just pure stupidity really. Upon hunting for the error, it was blatantly obvious and something I never thought I'd run into.

The metaphor of it goes like this... you send out messengers in regular intervals, but don't track them when you only need one messenger who is tracked. So all these anonymous messengers have information of what to get the update on, but it's only as recent as when they were sent. Therefore if they don't get back before the next one is sent for whatever reason, another messenger is sent for the same information. When they return, you now have double, possibly even triplicates of the same update info. So rather than handle that, it then dumps all the info in, duplicates and all, which then everything is overwhelmed, can't establish the right new request to make and then just shits itself.

Here's the remedy, and it should be the first thing you learn with Ajax requests. First, assign the object to a variable name. Then you check for two things, the readyState and the status. It's not done until the readyState is 4 and the status is 200. Once that is satisfied, then and only then do you send out a new request. This allows things that need to be done in order to be done in order.

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    // Process what to do when done.
}

You should preform this check even if you are waiting for the onreadystatechange event, as just because it has changed does not mean that it is done. Now for this particular script, it used a javascript framework called Prototype. When you create an Ajax object with that, the readyState and status are available in the object's transport object.

The bottom line is remember the flow and to control anything asynchronous, do not rely on delay or speed to maintain the flow in those cases.

Friday, December 23, 2011

Javascript setTimeout stop (clearTimeout)

I noticed a search query pointing to my site looking for how to stop a javascript setTimeout, and this is something I always forget. Here's the thing, when working with a timer, it emulates some form of multithreading/concurrency. Problems that can arise from this if you do things like timed animations on a triggered event are that if you don't stop a timer, you get multiple timers. This means at each trigger, you spawn a new timer to run with this emulated concurrency creating weird effects.

So to combat this, you want to use the method clearTimeout. This will take the argument of the integer returned when you call setTimeout. So when using this, you will also need to make sure you track that value.

var x = setTimeout(function() {
    alert("");
}, 1000);
clearTimeout(x);

This will appear not to do anything, but what it actually does is set the timer then clear it out. Now when you store the value, you can trigger an event to call the clearTimeout or you can initiate another setTimeout to have the clearTimeout run at some arbitrary time without a triggered event, like mathematically calculate a time to end some arbitrary animation without interrupting the main javascript code being executed or some such things. This method can also be called inside the timed function so long as it can clear the write variable, so make sure the scope is correct.

Monday, December 12, 2011

Javascript Exploit: setTimeout

When I was messing around with some javascript animation, I came across a rather strange exploit in javascript that can be taken advantage of to cause a little havoc on browsers. A quick explanation of javascript, when using an alert or other popup, that popup will pause the execution of the script until it is dealt with. However, setTimeout spawns another. This means using setTimeout, you can spawn multiple alert boxes or other such things that will pause and wait for input.

So then the question is how to use this to an exploit. A quick rough version would be something like
while (1){
  setTimeout(function (){
    alert("");
  }, 0);
}
This will create an infinite loop that will spawn alert boxes really fast, and probably freeze up or crash a browser. However due to browsers keeping javascript "sandboxed" for protection, there is a chance it will just say the script stopped responding and suspend it. This sandbox effect is to keep scripts from being able to interact with any other tabs or windows the user might have open as well as personal data stored, while not perfect, it can prevent certain exploits from causing damage.

Now alternatively, we could create a fork bomb. A fork bomb will multiply processes exponentially as apposed to what we have setup where it just increases directly. That will end up looking something like this.
function fork() {
  while (1){
    alert("");
    setTimeout(fork, 0);
  }
} fork();
This will then keep doubling but the effect will most likely be it just stops responding faster due to the sandbox setup. This could also have uses as this will fake multithreading by faking concurrency. So fake multithreading exploit is the bottom line.