How to insert HTML using Chrome extension? - javascript

I require my chrome extension to insert html into a page. I am able to insert the html, but am having issues styling the inserted element the way I want.
The image above is an example of what I'm looking for. I looked at the CSS for the grey box that was inserted and tried to implement those same things, but I get an error in the console when I try to do that.
The error I get:
Uncaught ReferenceError: Invalid left-hand side in assignment
The code I'm using to style it (CSS through JS):
(function() {
// just place a div at top right
var div = document.createElement('div');
div.style.position = 'fixed';
div.style.background-color = '505F69';
div.style.box-sizing = 'border-box';
// div.font-size = '16px';
div.style.top = 0;
div.style.right = 0;
// div.textContent = 'test';
div.style.zIndex = 1000000000;
div.innerHTML += 'Injected!';
document.body.appendChild(div);
})();
I get an error on line with "div.style.background-color" and "div.style.box-sizing".
Any advice on how to replicate this?

"div.style.background-color" and "div.style.box-sizing".
use
"div.style.backgroundColor" and "div.style.boxSizing".

Related

Filling CSS grid with JavaScript

I am working on a personal project with a canvas that is a CSS grid. It is 17 rows and columns and instead of adding 289 divs manually, that I would create a for loop to do it for me when the page loads.
JavaScript:
var row = 1;
var column = 1;
function init() {
for (var i = 0; i < 289; i++) {
var div = document.createElement("div");
div.style.color = "gray";
div.style.gridRow = row;
div.style.gridColumn = column;
column += 1;
if (column == 17) {
row += 1;
column = 0;
}
console.log("test");
}
}
HTML:
<body onLoad="init();">
<canvas id="myCanvas" width="600" height="600"></canvas>
</body>
This is the only 'version' that I've tried that doesn't spit an error at me, but still nothing shows up. It runs though, because the console displays "test".
I've tried replacing:
var div = document.createElement("div");
with
var div = document.canvas.createElement("div");`,
var div = document.myCanvas.createElement("div");
...etc. (which probably aren't the right syntax but I tried them anyway) and it gives me this error when evaluating document.myCanvas.createElement:
TypeError: undefined is not an object
Basically I just want each grid box in the canvas to be filled using JS when the page loads. Also, I'm very new to programming so simple terms are much appreciated. Thank you in advance.
I ended up creating a div that had the canvas inside it and replacing:
var div = document.createElement("div");
with:
var newDiv = document.createElement("div");
document.getElementById("background").appendChild(newDiv);
and it worked great.

addClass breaks JS

I wrote the following code:
document.addEventListener("DOMContentLoaded", ()=>{
let menu = document.querySelector(' #menu-mainmenu ');
menu.style.display = 'none';
});
let newButton = document.createElement(' div ');
This code didn't cause any problem.
The moment I've added the following code right under the let newButton, suddenly, as it seems, the JS broke (no JS would load properly anywhere in the site).
newButton.className = 'menuButton';
Console returns this error:
Uncaught DOMException:
Failed to execute 'createElement' on 'Document':
The tag name provided (' div ') is not a valid name.
Why would this happen? What is the problem with creating a div element this way?
You have extra spaces around the div tag and that cause an error. Remove them
document.addEventListener("DOMContentLoaded", ()=>{
//let menu = document.querySelector(' #menu-mainmenu ');
//menu.style.display = 'none';
console.log('Worked !!!');
});
let newButton = document.createElement('div');
newButton.className = 'menuButton';

Displaying Images in Javascript

OK, so I'm making a website in HTML, and it's working great, but I need to know how to display images on the page in javascript. I have in my website where there is a part on the homepage called news, and it's going to display an image about the topic, but I don't know how to display the image. When I use other website's ways, the image just displays as a square with a ? in the middle. Please help!!
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.appendChild(content);
I got these answers from:
How to display image with javascript?
How to append data to div using javascript?
This will work:
DEMO
javascript:
var i = document.getElementById('test'); //get the element to put the picture in
i.innerHTML = '<img src="http://pathtopicture.jpg"></img>'; // append the picture to the divs inner HTML
HTML:
<div id="test"></div>
Or without HTML in the first place (of course you need html and body tag...)
DEMO2
Code:
var i = document.createElement('div');
i.id = 'test';
document.getElementsByTagName('body')[0].appendChild(i);
i.innerHTML = '<img src="http://pathtopicture.jpg"></img>';

Creating Bootstrap Modal Dialog using JavaScript

I am trying to create a Bootstrap Modal dialog using JavaScript. The reason I am doing it with JavaScript is because I want to be able to render it later using custom elements (i.e. title, error message). I am fairly new to JavaScript so I do not understand why the code is not executed when I call the function errorMessage(). Can anyone please help out by letting me know what the mistake is and how I can correct it? Is there a more efficient way of doing it? Thank you very much.
By the way I did link the modal.js file to the HTML doc and I am aware of bootboxjs, but I don't want to use it for now.
// Creation of the alert message box.
function errorMessage() {
var Modal = document.createElement('div');
Modal.id = 'myModal';
Modal.className = 'modal fade show';
// To set up the attributes.
Modal.setAttribute("data-backdrop", "static");
Modal.setAttribute("data-keyboard", false);
document.body.appendChild(Modal);
var dialog = document.createElement('div');
dialog.className = 'modal-dialog';
Modal.appendChild(dialog);
var content = document.createElement('div');
content.className = 'modal-content';
dialog.appendChild(content);
var header = document.createElement('div');
header.className = 'modal-header';
content.appendChild(header);
var title = document.createElement('h4');
title.className = 'modal-title';
title.createTextNode = 'Data Error';
header.appendChild(header);
var body = document.createElement('div');
body.className = 'modal-body';
dialog.appendChild(body);
var message = document.createElement('p');
message.createTextNode("Oh... snap. We can't find any items in your list. Please make sure your entry is structured as following:");
body.appendChild(message);
var representation = document.createElement('div');
representation.className = 'well';
body.appendChild(representation);
var representationTxt = document.createElement('p');
representationTxt.style.fontStyle = 'italic';
representationTxt.createTextNode('> Subheader , tag1 , tag2, tag3');
representation.appendChild(representationTxt);
var footer = document.createElement('div');
footer.className = 'modal-footer';
dialog.appendChild(footer);
var closeBtn = document.createElement('button');
closeBtn.setAttribute("data-dismiss", "modal");
closeBtn.setAttribute("type", "button");
closeBtn.className = 'btn btn-primary btn-inverse';
closeBtn.value = 'I got it. Thanks.';
footer.appendChild(closeBtn);
// Show modal dialog box
$("#myModal").modal('show');
}
It is failing on this line: header.appendChild(header); because it cannot append header to itself. Did you mean this?
var title = document.createElement('h4');
title.className = 'modal-title';
title.createTextNode = 'Data Error';
header.appendChild(title);
A debugging tool is invaluable in javascript development (Firebug add-on for Firefox or the built-in tools in Chrome, for example). You would have seen this error right away :)

Block existing scripts

I am making an addon for firefox. I want to extract a video from a HTML page and display it on a black background. Here is what i've got.
//main.js
var pageMod = require("page-mod");
pageMod.add(new pageMod.PageMod({
include: "http://myserver.fr/*",
contentStyleFile: data.url("modify.css"),
contentScriptFile: data.url('hack.js'),
contentScriptWhen: 'start'
}));
//hack.js
video = document.body.innerHTML;
document.body.innerHTML = '';
video = video.substring(video.lastIndexOf("<object"),video.lastIndexOf("</object>"));
video = "<div id='fond'></div><div id='mavideo'>"+video+"</div>"
document.body.innerHTML = video;
document.body.style.backgroundColor = "black";
document.body.style.margin = "0";
My code works but the probleme is that I have to wait "for hours" while the other javascript is beeing executed. I've tried to use contentScriptWhen: 'start' but i dosent change a thing.
Any idea to block the other script of the page ?
Blocking scripts from loading is going to be a little difficult, we can quickly remove them instead.
// remove all scripts
var scripts = document.getElementsByTagName("script");
var parent = null;
for (var i = 0; i < scripts.length; i += 1) {
parent = scripts.item(i).parentNode;
parent.removeChild(scripts.item(i));
}
This code tries to remove all the script tags from your page which would stop the loading of any scripts and allows you to run the rest of your code. Put this at the top of your hack.js script.
I don't know the page you're looking at so it's hard to know what else is going on but your use of substring, and lastIndexOf aren't going to be very fast at all either. We can get rid of those and see if you get any noticible speed increase.
Try using query selectors and Document Fragments instead. Here's an example:
//hack.js
var fragment = document.createDocumentFragment();
var objects = document.getElementsByTagName("object");
// create your div objects and append to the fragment
var fond = document.createElement("div");
fond.setAttribute("id", "fond");
fragment.appendChild(fond);
var mavideo = document.createElement("div");
mavideo.setAttribute("id", "mavideo");
fragment.appendChild(mavideo);
// append all <object> tags to your video div
for (var i = 0; i < objects.length; i += 1) {
mavideo.appendChild(objects.item(i));
}
// clear and append it all in
document.body.innerHTML = '';
document.body.appendChild(fragment);
That code throws all the objects into a document fragment so you can wipe the whole page away and then append it all back in; no libraries required. Your divs fond & mavideo are in there as well.
I didn't really test all this code out so hopefully it works as expected.

Categories

Resources