copy a text / image generated in html - javascript

I would know if it's possible to copy in html a specific code section
As you see I receive a text and an image (enter image description here), In my console I can see the html code
<div class="row">
<div class="col-md-6">
<img src="https://images.pexels.com/photos/338504/pexels-photo-338504.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="Desktop" class="img-fluid">
</div>
<div class="col-md-6">
<p>Welcome to the world of desktops. Whether you’re looking for a powerful gaming PC or an everyday workstation, we have something to suit your needs. Our range of desktops are designed to provide the perfect balance between performance and portability, so you can stay productive wherever you are.</p> ...
</div>
</div>
I used the clipboard js to copy but it does not take in consideration the image and the html code.
Do you have any idea to resolve this and take in consideration just the html code generated ?
$(document).ready(function() {
// Initialize the clipboard
var clipboard = new ClipboardJS("#copyButton");
// Handler for when the copy button is clicked
clipboard.on("success", function(e) {
// Show a tooltip indicating that the text was copied
$(e.trigger).attr("data-original-title", "Copied!").tooltip("show");
e.clearSelection();
});
$("#send").click(function() {
let message = $("#messageGpt").val();
let engine = $("#engine").val();
$.post("' . $url . '", {message: message, engine: engine}, function(data) {
$("#TexArea-output").html(data);
// Show the copy button after the chat message is generated
$("#copyButton").removeClass("d-none");
});
});
});

Related

Using Tampermonkey to make an "ignore" button?

I have a script that goes as follows:
// ==UserScript==
// #name TempleOS Ignorer with added Braed Ignoring
// #include *://v3rmillion.net/*
// #grant none
// ==/UserScript==
const ignore = ['189822','695729', '1797404', '1439', '1290050', '941293', '1696676', '440792', '1391811', '114505']
new Array(...document.getElementsByClassName('author'))
.filter(author => ignore.includes(author.firstElementChild.getAttribute('href').match(/=([0-9]+)/)[1]))
.forEach(author => author.parentElement.parentElement.parentElement.remove())
new Array(...document.getElementsByClassName('author_information'))
.filter(author => ignore.includes(author.firstElementChild.firstElementChild.firstElementChild.getAttribute('href').match(/=([0-9]+)/)[1]))
.forEach(author => author.parentElement.parentElement.remove())
There's a div called post-head and I want to add a button to it that takes the user's ID and adds it to the ignore const. I'm fairly new to using Tampermonkey, most of this was done by someone else and I want to make it easier to add users to this ignore list. Something like this. (Very sloppily done, but you get the idea.)
So you can try taking a look at this script I came up with real quick, and then you can try putting it into a UserScript if you'd like. I tried to keep this extremely simple and basic. Just know there are plenty of ways to accomplish this, and this isn't exactly the standard in 2022. Otherwise, you can just copy this JS code into the Dev Tools Console tab on the message board, and it should work for you.
Here is the overall summary of what this is:
HTML is just basic message board HTML, the button is added next at the bottom of the post on the left side
Loops through each .post element on the page, using jQuery .each(), get the idof the post, and the id of the author.
There are probably tons of ways to get the author/post id from the markup on this message board. I simply chose to split() the URL using = and grab the ID at the array index of [2]. Getting the id of the post was just replacing the post_ from the id element on the .post element.
Left in the console.log() so it can be tested, output an alert() notification for button onclick
Appended the markup, which was created using String Literals to the .author-controls elements. I used an <a> element instead of a <button> because I didn't want to add any CSS to make it match.
const ignore = [];
$('.post').each(function() {
let US_pid = $(this).attr('id').replace('post_', '');
console.log('id=post_' + US_pid);
let US_author_id_array = $('.author_buttons > .postbit_find', this).attr('href').split('=')
let US_author_id = US_author_id_array[2];
console.log('author id: ' + US_author_id)
let US_ignore_btn_markup = `Ignore User`;
console.log(US_ignore_btn_markup);
$('.author_buttons', this).append(US_ignore_btn_markup);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post " style="" id="post_7747511">
<div class="post_head" style="padding-right:5px">
<div class="float_right" style="vertical-align: middle">
<strong><a class="postlink" href="showthread.php?pid=7747511#pid7747511" title=""></a></strong>
</div>
</div>
<div class="post_author">
</div>
<div class="post_content">
</div>
<div class="post_controls">
<div class="postbit_buttons author_buttons float_left">
<span>PM</span>
<span>Find</span>
</div>
<div class="postbit_buttons post_management_buttons float_right">
<span>Report</span>
</div>
</div>
</div>

update the content of clipboard in prismjs

I have code snippet, which user can copy to his/her site. I use prismjs to show html code. also it has copy button, so user can copy the code in clipboard, it uses clipboardjs for this. user can choose between different options(this is the list like <select><option>..), which will update the code snippet and also should update the content of clipboard button(here's issue).
here's html
<pre class="language-html">
<code id="code-example">
<!-- <div class="widget widget-BTC" data-fiat="EUR"></div> -->
</code>
</pre>
after user choose different options, the content of <code id="code-example"> will be updated (it updates the class name and data-fiat attribute)
here's js code which does update:
let block = document.getElementById('code-example');
block.innerHTML = '<!-- <div class="widget ...';
Prism.highlightElement(block);
the issue is, when I choose other option from select list, it updates html code snippet, but if I click the copy button, it copies the old value, not updated one. I tried different things like here but still same issue.
It needs to create another object to update the value. here's solution:
new Clipboard('.yourButton', {
text: function(trigger) {
return '<div>some text</div>';
}
});

Save HTML element locally in Javascript

My Snippet tool allows users to save/copy code snippets in order to share them. I use html2canvas in order to display the snippet that the user has created in the console and allow them to save it.
But I have found many problems in their display on browsers other than Firefox, as you can see here (it's blurry and the letter spacing is abnormal).
Here's how I save the snippet once the user presses "Save":
// Call html2canvas with the console element
html2canvas(document.getElementsByClassName('console'), {
onrendered: function(canvas) {
var url = canvas.toDataURL()
// Set the element's URL in an img tag
var img = '<img src="' + url + '" style="border:0;"></img>'
// Open a window and display the image in it
var x = window.open();
x.document.open();
x.document.write(img);
x.document.close();
}
});
My best solution at the moment is to have the snippet saved locally and directly to the user, how may I have a specific HTML element downloaded using Javascript?
EDIT:
This is the HTML element that I wish to save, it contains the console design and a codemirror component that represents the text editor in which users type:
<div class="console">
<div class="console-header">
<div class="console-buttons">
<div class="console-button button-1"></div>
<div class="console-button button-2"></div>
<div class="console-button button-3"></div>
</div>
</div>
<div class="console-content">
<codemirror [(ngModel)]="content" [config]="config"></codemirror>
</div>
</div>

How do I upload image/s and store in Local Storage (angularjs)

What I want to do…
User clicks ‘upload image’ button
User selects an image from local machine
Image is uploaded to the page
Image is stored in local storage
User can navigate away from view and then return to the view and see the previously uploaded images.
Repeat steps 1 - 5
How I think I can achieve it…
ng-flow plugin to manage user uploads
convert image to base64 and store image as string in local storage
get base64 string and convert it to image for preview.
Why I want to do this…
For phase 1 I need to show my tutor how my application will work, so I just need to imitate the images stored in a database, this is why I'm using local storage - I understand this is bad practice but I also need to show use of local storage.
My tutor encouraged me to use stack overflow and knows I posted this.
Code so far…
My view
<!-- Upload multiple images with the extensions of png,jpg, jpeg & gif -->
<div flow-init="{target: '/upload', singleFile: false}" flow-file-added="!!{png:1,gif:1,jpg:1,jpeg:1}[$file.getExtension()]" flow-files-submitted="$flow.upload()">
<div class="jumbotron">
<div class="container">
<div><span class="btn btn-default btn-selectimage" flow-btn flow-attrs="{accept:'image/*'}" onchange="previewFile()">Select image</span></div>
<br><p>Only PNG,GIF,JPG files allowed.</p>
</div>
</div>
<div>
<div class="thumbnail" ng-hide="$flow.files.length">
<img src="images/no-images-placeholder.jpg" />
</div>
<div class="thumbnail col-md-3" ng-show="$flow.files.length" ng-repeat="image in $flow.files">
<img id="image-handle" class="preview-blob" flow-img="image" /><br>
<img class="preview" ng-src="{{imageStrings[$index]}}"/>
<div class="image_option_controls">
<span class="btn glyphicon glyphicon-trash" ng-show="$flow.files.length" ng-click="image.cancel()"></span>
<span class="btn glyphicon glyphicon-heart pull-right" ng-click="image.like()"></span>
</div>
</div>
</div>
</div>
My Controller - so far...
angular.module ( 'myApp' )
.controller (
'ProtectedCtrl', function ($localStorage, $scope)
{
var myImage = [];
$localStorage.myImage = document.getElementById('image-handle');
console.log($localStorage.myImage);
});
I can select images and preview them on the page, when I inspect the page the image src has been converted to base 64. From this point on I'm stuck on how to get the base 64 string and store it.
Sorry for the rookie post, any tips or pointers would be greatly appreciated.
Thanks in advance!
I recently read an article for the very same purpose and one way to do this for an image, is to load into a canvas element. Then, with a canvas, you can read out the current visual representation in a canvas as a Data URL. Following is the code snippet
// Get a reference to the image element
var elephant = document.getElementById("elephant");
// Take action when the image has loaded
elephant.addEventListener("load", function () {
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");
// Save image into localStorage
try {
localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
console.log("Storage failed: " + e);
}
}, false);
DataURL is a base64 string as localstorage cannot store images directly and It is not that common to store images in localstorage. I maybe wrong though. However, here is a link that is gonna link help you further https://hacks.mozilla.org/2012/02/saving-images-and-files-in-localstorage/

JQuery find element in script

I am really not great at web stuff, so I am apologizing in advance for a potentially poor explanation of my problem.
Basically, I have a webpage which utilizes the handlebars js templating. Unfortunately, this means that many of my div elements are contained within javascript tags like the following:
<script type="text/x-handlebars" data-template-name="index">
<div class="row intro">
......
</div>
<div class="descript">
.....
</div>
</script>
My intent is to grab one of these div elements using jquery.find(), but from what I understand, the html within the script tags is not treated as part of the dom...so jquery does not see it as a dom element. I was wondering if there is any other way I could go about this. Some more code is included.
Here is another more explicit explanation in case the one I gave above was a little muddled: I am working on a personal website and would like to embed a project I have been working on in unity3d, but I need to add/remove elements based on whether or not the client has the unity3d web player installed. Normally I would get a particular element with
var $missingScreen = jQuery("#unityPlayer").find(".missing");
where 'missing' is simply an element inside unityPlayer which displays a link if the client does not have unity3d. I am also using some javascript templating to make my site look pretty and as a result, I have this problem:
<script type="text/x-handlebars" data-template-name="index">
<div class="row intro">
<div class="intro-text">Hi, I'm *****</div>
</div>
<div class="descript">
<p>
Here's a Project I have been working on in case I am of interest to you:
</p>
</div>
<div class="content">
<div id="unityPlayer">
<div class="missing">
<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now!">
<img alt="Unity Web Player. Install now!" src="http://webplayer.unity3d.com/installation/getunity.png" width="193" height="63" />
</a>
</div>
</div>
</div>
<p class="footer">« created with Unity »</p>
</script>
Jquery cannot access the missing element. Is there any way to do this? Thanks for any help you can give me and sorry again for my inexperience.
EDIT* some people might want to know: here is how I determine whether or not to show the missing div. Another note; everything works fine if I remove the script tags...it is only when I put html within the script tags that it becomes inaccessible to jquery.
jQuery(function() {
var $missingScreen = jQuery("#unityPlayer").find(".missing");
$missingScreen.hide();
u.observeProgress(function (progress) {
switch(progress.pluginStatus) {
case "missing":
$missingScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$missingScreen.show();
break;
case "installed":
$missingScreen.remove();
break;
case "first":
break;
}
});
u.initPlugin(jQuery("#unityPlayer")[0], "temmp.unity3d");
});
Instead of
var $missingScreen = jQuery("#unityPlayer").find(".missing");
I would try out
var $missingScreen = jQuery("#unityPlayer").children(".missing");
or
var $missingScreen = jQuery("#unityPlayer .missing");
Don't forget the space between Player and .missing!
I hope it works.

Categories

Resources