Reputation: 1964
I would like to generate code pen link with pre-filled css data.
How can I do it programmatically in javascript?
I tried posting the pre-filled data to code pen but not able to generate codepen link programmatically.
Upvotes: 1
Views: 579
Reputation: 17325
In theory you could also use a <a>
link element as well – avoiding the <form>
element and making it shareable. But this approach is almost unusable.
The main problem: Due to the maximum character limit for GET
variables ~2000 characters we can only create very tiny codepens.
<p>
<a id="link" href="https://codepen.io/pen/define?data=%7B%22title%22%3A%22New%20Pen!%22%2C%22html%22%3A%22%3Cdiv%3E%27Hello%2C%20World!%27%3C%2Fdiv%3E%22%7D" target="_blank">Create prefilled codepen Link </a>
</p>
Provided, the GET data
JSON is encoded correctly it works.
For encoding you could use encodeURIComponent()
.
To give you an idea about the character limit:
let props = {
title: "New Pen!",
html: "<p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a <em>horrible vermin.</em></p>",
css: `
@font-face {
font-family: 'ABeeZee';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/abeezee/v22/esDT31xSG-6AGleN2tCUnJ8DKpE.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'ABeeZee';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/abeezee/v22/esDR31xSG-6AGleN2tWkkA.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
body{
font-family: 'ABeeZee';
font-weight: 400;
color:red;
font-size:10em;
}`
};
let data = JSON.stringify(props);
let url = `https://codepen.io/pen/define?data=${encodeURIComponent(data)}`;
console.log('url length:', url.length)
link.href = url;
<p>
<a id="link" href="" target="_blank">Create prefilled codepen Link </a>
</p>
Although the above example is quite simple and contains only 2 font-face rules and a single paragraph it already scratches the limit (1725 chars).
Upvotes: 0
Reputation: 24630
You should use CodePen API for that.
Example:
<form action="https://codepen.io/pen/define" method="POST" target="_blank">
<input type="hidden" name="data" value='{"title": "New Pen!", "html": "<div>Hello, World!</div>"}'>
<input type="submit" value="Create New Pen with Prefilled Data">
</form>
More info:
Upvotes: 1