Chrome extension inject html to specific div - google-chrome

Im trying to make an extension for chrome that injects html code to specific div on a specific page.
This is the example page I want to inject some code:
http://netdna.webdesignerdepot.com/uploads7/creating-a-modal-window-with-html5-and-css3/demo.html
So far I have made this:
manifest.json:
{
"manifest_version": 2,
"content_scripts": [ {
"js": [ "iframeInjector.js" ],
"matches": [ "http://netdna.webdesignerdepot.com/*/*/*"
]
} ],
"description": "Inject html",
"name": "Inject html",
"version": "1",
"web_accessible_resources": ["test.html"]
}
test.html:
Test html code
iframeInjector.js:
var iframe = document.createElement ("iframe");
iframe.src = chrome.extension.getURL ("test.html");
document.body.insertBefore (iframe, document.body.openModal);
On the example page there is div called "openModal", how do I inject my html code into that div ?
Another question: Is there way to read page title to variable and use that variable in my html code which Im infecting ?
Thank you..

So there is a div with id="openModal" to which you want to append the iframe?
iframeInjector.js
var iframe = document.createElement ("iframe");
iframe.src = chrome.extension.getURL ("test.html");
var yourDIV = document.getElementById("openModal");
yourDIV.appendChild(iframe);

Related

add html edit button to quill in angular

I would like to make a custom toolbar for my quill editor. Therefore I would like to add another button to the toolbar for converting the text I enter into html code. I have tried several methods but they didn't work out. Please help me with an idea.
What i have in component.html:
<quill-editor [styles]="{height: '200px'}" [modules]="editorModules" (onEditorChanged) = "changedEditor($event)"></quill-editor>
And here is what i have in component.ts:
editorText='';
editorModules = {
toolbar: [
['bold', 'italic', 'underline'],
[{align:''}, {align:'center'}, {align:'right'}, {align: 'justify'}],
[{'indent': '-1'},{'indent': '+1'} ],
[{'size' : ['small', false, 'large', 'huge']}],
['color'],
['link'],
[{'list': 'bullet'}, {'list': 'ordered'}],
['image']
]
}
changedEditor(event: EditorChangeContent | EditorChangeSelection) {
console.log('editor got changed');
this.editorText = event['editor']['root'];
}
Here is a photo of my current Text Editor:
Text Editor
I would very much appreciate if you would try to help me, thank you.

Ckeditor allowedContent for html tag

I am using Ckeditor as rich editor for text input in the Chrome browser. I also have added some html id tag for easy parsing by bs4 after the system getting the data.
The following is my setting in the html:
CKEDITOR.replace( 'editor', {
toolbar : 'Basic',
uiColor : '#9AB8F3',
height : '70%',
startupShowBorders: false,
})
And in the config.js:
config.toolbarGroups = [
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
{ name: 'links' },
{ name: 'insert' },
{ name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
{ name: 'styles' },
{ name: 'colors' },
{ name: 'about' }
];
// Remove some buttons provided by the standard plugins, which are
// not needed in the Standard(s) toolbar.
config.removeButtons = 'Underline,Subscript,Superscript';
// Set the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre';
// Simplify the dialog windows.
config.removeDialogTabs = 'image:advanced;link:advanced';
config.allowedContent = True;
};
Although I have already followed the instruction to allow all html tag content to be preserved with config.allowedContent = *; in the config.jd. However, it seems not working as I got the following results when getting data (by CKEDITOR.instances.editor.getData()):
<span style='font-size:11.0pt;'> content </span>
instead of this that I want:
<span id="news_content" style='font-size:11.0pt;'> content </span>
In other words, it still strips out all the html tag I added.
When I checked the source code, I found that the same textarea content was produced twice with the one with the tag being put in hidden format, i.e.,
<textarea name="editor" id="editor" rows="100" cols="40" style="visibility: hidden; display: none;">
And the editor produces another version in the real textarea that allows me to edit. However, this is useless because all the html tags are stripped there.
So, my question is, how to preserve the html tag in the real textarea so that I can parse the html with id tags after editing and submission. Could anyone advise on this? Thanks a lot.
I may not be able to answer my own question, but I like to share my solution with those encountering similar situation.
In short, finally I give up using ckeditor or any plug-in editor as many of them will strip off the html tag, which is essential to me in the subsequent process.
Thanks to html5, my solution is using editable div. The setting is very simple as below:
css:
#my-content {
box-shadow: 0 0 2px #CCC;
min-height: 150px;
overflow: auto;
padding: 1em;
margin: 5px;
resize: vertical;
outline: none;
}
html:
<div id="my-content" class="editable" style="width:900px; height:400px; text-overflow: ellipsis; overflow-y: scroll;"></div>
js script:
$('.editable').each(function(){
this.contentEditable = true;
});
So far, I am happy with it, it shows what exactly the html code showing and preserve all the tags I added. The only downside is it does not provide any toolbar for format editing. My solution is to make one for it, and via the following link you can get a very good tutorial as to making a toolbar with a ready-to-use demo as illustration.
https://code.tutsplus.com/tutorials/create-a-wysiwyg-editor-with-the-contenteditable-attribute--cms-25657
Hope this helps.

How to show a modal popup from the context menu?

How can I display a modal dialog from the context menu?
I can show a new window from context menu which opens in its own tab:
var menuItem = {
"id": "rateMenu",
"title": "Rate Item",
"contexts": ["all"],
}
chrome.contextMenus.create(menuItem);
chrome.contextMenus.onClicked.addListener(function (clickData) {
open('index.html');
});
I also know how to show a modal dialog, using bootstrap (for example) on the page itself:
$('#myModal').modal({
backdrop: 'static',
keyboard: false
})
In this particular case I want to show a modal dialog that you cannot close unless you press the "close" button.
However, I have no idea how to show the modal popup window straight away from the context menu.
Does anyone have any idea how this can be achieved?
Thank you!
I have done the same. Just use content script to show modal.
Example : When user clicks the context menu item, send message to content script to let it know about it so that it should open a modal.
background.js:
chrome.contextMenus.onClicked.addListener(function (clickData) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type: "openModal"});
});
});
contentscript.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
switch (request.type){
case "openModal":
$('#myModal').modal({
backdrop: 'static',
keyboard: false
});
break;
});
Make sure to include necessary css and js files under content_scripts in manifest.json
"content_scripts": [
{
"matches": ["https://*/*"],
"css":["bootstrap.min.css"],
"js":["jquery.min.js","bootstrap.min.js","contentscript.js"],
"run_at":"document_end"
}
]
NOTE : Using bootstrap.min.css may conflict with the page UI and it may change it. To avoid this, move your modal and the required js and css files in a separate html file(modal.html). Then inject your iframe into the tab using content script.
var iframe = document.createElement('iframe');
iframe.src = chrome.extension.getURL("modal.html");
iframe.frameBorder = 0;
iframe.id = "myFrame";
$(iframe).hide();//necessary otherwise frame will be visible
$(iframe).appendTo("body");
Remember to add modal.html and all the css and js files that are used inside modal.html like modal.js,bootstrap.min.js,bootstrap.min.css under web_accessible_resources:
web_accessible_resources": ["modal.html","modal.js","bootstrap.min.js","bootstrap.min.css"]
Now you can hide or show your iframe using content script but to show and hide modal, it can be done from inside iframe only. So you would need to pass a message from background to iframe to show the modal.The code above mentioned for contentscript will work for iframe also.
In case you want to hide the iframe, just send message from iframe to contentscipt using window.parent.postMessage().
Example:
modal.js:
window.parent.postMessage({ type: "hideFrame" }, "*");
contentscript.js:
window.addEventListener("message", function(event) {
if (event.data.type == "hideFrame") {
$("#myFrame").hide();
}
});

HTML : How to retain formatting in textarea?

I am using HTML textarea for user to input some data and save that to App Engine's model
The problem is that when I retrieve the content it is just text and all formatting is gone
The reason is because in textarea there is no formatting that we can make
Question:
is there any way to retain the format that user provides?
is there any other element(other than textarea), that i'll have to use?(which one?)
P.S I am very new to area of web development and working on my first project
Thank you
What you want is a Rich Text Editor. The standard HTML <textarea> tag only accepts plain text (even if the text is or includes HTML markup). There are a lot of example out there (including some listed on the page linked) but I would highly recommend using a prepackaged one for this. Coding your own is fairly complicated for people who are new, and even for a lot who have some experience. Both TinyMCE and CKEditor are very common ones, but there are many others as well.
A text box is like wordpad, you cant format it, if you paste in from word or any other formatted text it will wipe all the formatting and you will be left with just the text.
You need add an editor to the text areas, I use TinyMCE, but there are many other out there too.
To implement you need to have all the source (which you can get from TinyMCE) in your web directory.
Here's an example which you can try:
Add this the the head section of your page:
<script language="javascript" type="text/javascript" src="/js/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
theme : "advanced",
mode: "exact",
elements : "elm1",
theme_advanced_toolbar_location : "top",
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,"
+ "justifyleft,justifycenter,justifyright,justifyfull,formatselect,"
+ "bullist,numlist,outdent,indent",
theme_advanced_buttons2 : "link,unlink,anchor,image,separator,"
+"undo,redo,cleanup,code,separator,sub,sup,charmap",
theme_advanced_buttons3 : "",
height:"350px",
width:"600px"
});
</script>
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "textareas",
theme : "advanced",
plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
// Skin options
skin : "o2k7",
skin_variant : "silver",
// Example content CSS (should be your site CSS)
content_css : "css/example.css",
// Drop lists for link/image/media/template dialogs
template_external_list_url : "js/template_list.js",
external_link_list_url : "js/link_list.js",
external_image_list_url : "js/image_list.js",
media_external_list_url : "js/media_list.js",
// Replace values for the template plugin
template_replace_values : {
username : "Some User",
staffid : "991234"
}
});
</script>
Then to call the textarea:
<textarea name="content" style="width:100%">YOUR TEXT HERE</textarea>
NB: You need to download and have in your directory the js files for <script language="javascript" type="text/javascript" src="/js/tiny_mce/tiny_mce.js"></script>
Hope this helps!
This won't solve the case when you want somebody to be able to format their text (e.g. with WYSIWYG bold buttons etc.), but if you want to be able to accept pre-formatted HTML (e.g. copy and paste from other HTML source such as a webpage), then you can do this:
<form ...>
<label>Paste your HTML in the box below</label>
<textarea style='display:none' id='foo'></textarea>
<div id='htmlsource' contenteditable style='border:solid 1px black;padding:1em;width:100%;min-height:2em;' ></div>
<input type='submit' />
</form>
<script>
jQuery(function(){
jQuery('form').submit( function(e) {
jQuery('textarea').val( jQuery('#htmlsource').html() );
});
});
</script>
This uses a contenteditable div element which you can format to look like an input box and will accept pasted HTML, and a hidden textarea#foo which will be populated with the pasted HTML just before the form is submitted.
Note that this is not an accessible solution as it stands.
Depending on your goal for the programm it could already be sufficient to just add "pre" tags left and right to the input of your textarea. for example if your code submits to a form whatever is inside a textarea and than echos it in the target File this would already work.
> File 1:
>
> <form action="Output.php" methode=post>
> <textarea name="Input"></textarea>
> </form>
>
> File Output.php
>
> $UserInput = $_POST["Input"];
> $UserInput = "<pre>" . $UserInput . "</pre>"
> echo $UserInput
this already will retain all Enters for example that where used in the original user input and echo them correctly
If you retrieve the content from the App Engine Saving the Content with the pre tags added already in most cases does the trick

Show/Hide DIV Chrome Extension

What I'm trying to achieve is simple.
Now there's an extension already made called Note Anywhere. Notice when you click the app's icon the sticky note displays on the webpage, and you're able to drag, and drop that div anywhere you want.
What I'm trying to achieve is very similar.
Click #1 fades div in
Click #2 fades div out
I'll worry about drag and drop once I can get the div to actually show. I've spent over 16 hours trying to achieve this effect, and after getting extremely agitated I had to edit my question, and ask once more with updated info. So this will no longer be a problem again.
Here's my code.
Manifest:
{
"name": "CamDesk",
"version": "0.0.1",
"description": "The Desktop Webcam Widget",
"permissions": ["tabs", "http://*/*", "https://*/*"],
"background_page": "background.html",
"browser_action": {
"default_icon": "images/logo.png",
"default_title": "CamDesk"
},
"content_scripts": [ {
"matches": ["http://*/*", "https://*/*"],
"css": ["css/style.css"],
"js": ["js/jquery.js", "js/jquery-swfobject.js", "js/background.js"]
} ],
"icons": {
"48": "images/48x48.png",
"256": "images/logo.png"
}
}
CSS:
.camdesk {
display:none;
width:320px;
height:240px;
background-color:#FFF;
box-shadow:0px 4px 16px rgba(0, 0, 0, 0.8);
overflow:hidden;}
Background Page:
<html>
<head>
<script src="js/background.js"></script>
</head>
<div id="camdesk">
Please install the most recent version of flash to use CamDesk.
</div>
</html>
Content Script: "To Show & Hide DIV"
$(document).ready(function() {
$('.camdesk').flash({
swf: './camdesk.swf',
width: 320,
height: 240
});
});
chrome.browserAction.onClicked.addListener(getMessage);
getMessage();
function getMessage() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(null, function(tab) {
$('.camdesk').fadeOut(350);
}); //getting response from content script
});
}
chrome.extension.onRequest.addListener(
function(sendResponse) {
if $('.camdesk').fadeIn(350);
$('.camdesk').fadeOut(350);
else
sendResponse({});
});
To create that effect, you need to use Content Scripts. That is the only way you can manipulate the DOM for a website your visiting. Since your coming from the extension context (Browser Action button), you need to use Message Passing to transfer commands to show/hide to the DOM.
So the steps to achieve what you need:
Instantiate a chrome.browserAction.onClicked.addListener in the Background Page
Use chrome.tabs.sendRequest to tell the DOM what to do. You need to send a message asking it to Show or Hide the overlay you wanted.
Listen on extension requests from the Content Script using chrome.extension.onRequest.addListener When you receive a Show or Hide command from the extension, you can add/remove the DOM.
Hope that gives you a slight push!