I am trying to read the pages CSS using a chrome extension. This is what i have in my content script :
var allSheets = document.styleSheets;
for (var i = 0; i < allSheets.length; ++i) {
var sheet = allSheets[i];
var src = sheet.href;
var rules = sheet.cssRules || sheet.rules;
}
For some reason the rules are always empty. I do get all the CSS files used in the 'src' variable. But the rules always come as null.. Its working when I try it as a separate javascript on a HTML page. But fails when I put it up in the content script of my chrome extension. Can somebody lemme know why?
Well thats the Why, but for fun and interest (never done anything with style sheets before) I thought Id do a How....
manifest.json
{
"name": "Get all css rules in stylesheets",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js" : ["myscript.js"],
"run_at":"document_end"
}
],
"permissions": [
"tabs", "<all_urls>"
],
"version":"1.0"
}
myscript.js
// Create the div we use for communication
var comDiv = document.createElement('div');
comDiv.setAttribute("id", "myCustomEventDiv");
document.body.appendChild(comDiv);
// Utitlity function to insert some js into the page, execute it and then remove it
function exec(fn) {
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + fn + ')();';
document.body.appendChild(script); // run the script
document.body.removeChild(script); // clean up
}
// function that gets inserted into the page
// iterates through all style sheets and collects their rules
// then sticks them in the comDiv and dispatchs the event that the content script listens for
getCSS=function (){
var rules = '';
// Create the event that the content script listens for
var customEvent = document.createEvent('Event');
customEvent.initEvent('myCustomEvent', true, true);
var hiddenDiv = document.getElementById('myCustomEventDiv');
var rules ='';
var allSheets = document.styleSheets;
for (var i = 0; i < allSheets.length; ++i) {
var sheet = allSheets[i];
for (var z = 0; z <= sheet.cssRules.length-1; z++) {
rules = rules +'\n'+ sheet.cssRules[z].cssText;
}
}
hiddenDiv.innerText = rules;
hiddenDiv.dispatchEvent(customEvent);
}
// puts the rules back in the page in a style sheet that the content script can iterate through
// youd probably do most of this in the injected script normally and pass your results back through the comDiv....Im just having fun
document.getElementById('myCustomEventDiv').addEventListener('myCustomEvent', function() {
var eventData = document.getElementById('myCustomEventDiv').innerText;
document.getElementById('myCustomEventDiv').innerText='';
var style = document.createElement('style');
style.type = 'text/css';
style.innerText=eventData;
style = document.head.appendChild(style);
var sheet = document.styleSheets[document.styleSheets.length-1];
for (var z = 0; z <= sheet.cssRules.length-1; z++) {
console.log(sheet.cssRules[z].selectorText +' {\n');
for (var y = 0; y <= sheet.cssRules[z].style.length-1; y++) {
console.log(' '+sheet.cssRules[z].style[y] + ' : ' + sheet.cssRules[z].style.getPropertyValue(sheet.cssRules[z].style[y])+';\n');
};
console.log('}\n');
};
// Clean up
document.head.removeChild(style);
document.body.removeChild(document.getElementById('myCustomEventDiv'));
});
exec(getCSS);
In the case of this question Id prolly do most of the checks in the injected script and then pass the results back through the div and its event. But I wanted to see if I could use the dom methods in the content script to go through the css and this was the only way I could figure to do it. I dont like the idea of inserting the rules back into the page, but couldnt figure any other way of doing it.
Just a guess, but since chrome extensions are Javascript based, they may have cross domain issues. Chrome sets the rules and cssRules to null when programmatically trying to get a stylesheet from another domain.
For getting all external css and all internal css file, you can use devtools API. If you want to use it in chrome extension you need to hook devtool into you chrome extension. This code will work
chrome.devtools.panels.create(
'my chrome extension',
'icon.png',
'index.html',
function(panel) {
var initial_resources = {};
// collect our current resources
chrome.devtools.inspectedWindow.getResources(function(resources) {
for (var i = 0, c = resources.length; i < c; i++) {
if (resources[i].type == 'stylesheet') {
// use a self invoking function here to make sure the correct
// instance of `resource` is used in the callback
(function(resource) {
resource.getContent(function(content, encoding) {
initial_resources[resource.url] = content;
});
})(resources[i]);
}
}
});
}
);
Answer is late, but I think I can help. One method of accessing the cssRules of external sheets protected by CORs is to use Yahoo's YQL service. I've incorporated it into a developer tools extension for Chrome for capturing styles and markup for a page fragment. The extension is in the Chrome Web Store and is on Github.
Grab the source from Github and look at the content.js script to see how YQL is used. Basically, you'll make an AJAX call to YQL and it will fetch the CSS for you. You'll need to take the CSS content and either inject it into the page as an embedded style tag or parse the CSS using JavaScript (there are some libraries for that purpose). If you choose to inject them back into the document, make sure to set the new style blocks to disabled so that you don't screw up the rendering of the page.
The extension itself might be useful to you:
Related
I am building a classified ads website (like craigslist) with: handlebars (hbs), nodejs and multer for uploading images.
I have already created my own CRUD.
Users could post their ads for free, introducing their info for each ad:
user name
email
ad title
ad description
ad city
ad category
ad images (more than one if user needs)
I have a view, list.hbs, where ads show its information:
When users clicks on ad pictures, it will open like a modal box / pop up:
Everything perfect until here.
I save pictures in my ad.model, through multer like this:
image: {
imgName:{
type:String
},
imgPath:{
type:[String]
}
}
As you can see, I store path's pictures in an array to my mongodb database (managed by mongoose).
I.e:
"image" : {
"imgPath" : [
"uploads/e3c97fb10dd4c602054bedce194464b6",
"uploads/302fe7e147932d2b868a79b1799ba3f9"
]
}
The problem is here. I 've been trying to change image after clicking in each picture and it is impossible to do it.
I have tried via , but it looks like hbs doesn't work properly and don't read variables from handlebars:
I even tried passing through helper via onclick = myfunction({{#imageHelper}}{{/imageHelper}}), but it doesn't work...
Anybody knows how to handle this in handlebars? How to add js code to this view?
Note: my modal box / pop up is made it with pure html / css, no js or jquery in there.
I can't believe my mistake, how I didn't noticed before!
If you reach this question, or any question linked to handlebars - multer - javascript DOM, please, don't forget that template variables inside an onclick element MUST be quoted.
Mistake / Error
I passed through onclick element this:
<img onclick="myFun({{ad.reference}},{{ad.image.imgPath}})" class="imgAd" id="{{ad.reference}}" src="{{ad.image.imgPath.[0]}}"/>
And to manage the src and change images clicking everywhere on the image, I tried to do this:
...
<script>
let i = 0;
//next prev image
function myFun(ref,str){
const arr = str.split(',');
const len = arr.length;
if(i < len - 1){
i = i + 1;
document.getElementById(ref).src = arr[i]
}
else {
i = 0;
document.getElementById(ref).src = arr[i]
}
}
</script>
(This script above, just for change next picture, and so on)
Remember: if you pass variables like that, not quoted, js will throw errors, because it receives a "variable" like parameter, not a string.
In this case onclick received this:
uploads/b5e01da1707382ed915f314c0c77266c //variable, not string
Correct way:
<img onclick="myFun('{{ad.reference}}','{{ad.image.imgPath}}')" class="imgAd" id="{{ad.reference}}" display="block" src="{{ad.image.imgPath.[0]}}"/>
I passed a string, not a variable:
After I quoted each handlebar variable, I passed as string.
"uploads/b5e01da1707382ed915f314c0c77266c"
Now, the script will works. I get a string that I need to transform in an array to handle it:
<script>
let i = 0;
//next prev image
function myFun(ref,str){
const arr = str.split(',');
const len = arr.length;
if(i < len - 1){
i = i + 1;
document.getElementById(ref).src = arr[i]
}
else {
i = 0;
document.getElementById(ref).src = arr[i]
}
}
</script>
With this, I was able to manage DOM in each ad, changing images after clicking with nodejs, hbs and multer.
Meteor merges all (s)css files together as part of the build process and generates a single css file called /merged-stylesheets.css?biglongnumber
I'm using TinyMCE in a Meteor app and I want the content within the TinyMCE window to use the same css as the page it's on. TinyMCE has the ability to do this:
tinyMCE.init({
content_css : '/myStyles.css'
});
So I want to get the path to that merged stylesheet so I can pass it to TinyMCE. Is there a way to do this?
You can get the URL of the CSS files on the current page using the browser DOM, then make a comma-separated list of them and give it to TinyMCE. The following gets only the CSS files matching the current domain (& port and scheme):
//Get CSS files being used
var schemeDomainPort = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
var cssFiles = '';
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(schemeDomainPort) === 0) {
cssFiles += cssFiles ? ',' + document.styleSheets[i].href : document.styleSheets[i].href;
}
}
//Configure TinyMCE
$scope.tinymceOptions = {
content_css: cssFiles,
...
}
From a xul-based firefox addon, I need to:
programmatically create an invisible iframe (once)
reuse it to load multiple URLs as the addon runs
access the returned HTML after each URL loads
Problem: I can only get the first page-load for any created iframe to trigger an 'onload' or 'DOMContentLoaded' event. For subsequent URLs, there is no event triggered.
Note: I'm also fine with using the hiddenDOMWindow itself if this is possible...
Code:
var urls = ['http://en.wikipedia.org/wiki/Internet', 'http://en.wikipedia.org/wiki/IPv4', 'http://en.wikipedia.org/wiki/Multicast' ];
visitPage(urls.pop());
function visitPage(url) {
var XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
var hiddenWindow = Components.classes["#mozilla.org/appshell/appShellService;1"].getService
(Components.interfaces.nsIAppShellService).hiddenDOMWindow;
var doc = hiddenWindow.document, iframe = doc.getElementById("my-iframe");
if (!iframe)
{
iframe = doc.createElement("iframe");
//OR: iframe = doc.createElementNS(XUL_NS,"iframe");
iframe.setAttribute("id", "my-iframe");
iframe.setAttribute('style', 'display: none');
iframe.addEventListener("DOMContentLoaded", function (e) {
dump('DOMContentLoaded: '+e.originalTarget.location.href);
visitPage(urls.pop());
});
doc.documentElement.appendChild(iframe);
}
iframe.src = url;
}
There are some traps:
The hiddenWindow differs between platforms. It is XUL on Mac, and HTML else.
You should use .setAttribute("src", url); to reliably navigate.
The following works for me (Mac, Win7):
var urls = [
'http://en.wikipedia.org/wiki/Internet',
'http://en.wikipedia.org/wiki/IPv4',
'http://en.wikipedia.org/wiki/Multicast'
];
var hiddenWindow = Components.classes["#mozilla.org/appshell/appShellService;1"].
getService(Components.interfaces.nsIAppShellService).
hiddenDOMWindow;
function visitPage(url) {
var iframe = hiddenWindow.document.getElementById("my-iframe");
if (!iframe) {
// Always use html. The hidden window might be XUL (Mac)
// or just html (other platforms).
iframe = hiddenWindow.document.
createElementNS("http://www.w3.org/1999/xhtml", "iframe");
iframe.setAttribute("id", "my-iframe");
iframe.addEventListener("DOMContentLoaded", function (e) {
console.log("DOMContentLoaded: " +
e.originalTarget.location);
var u = urls.pop();
// Make sure there actually was something left to load.
if (u) {
visitPage(u);
}
});
hiddenWindow.document.documentElement.appendChild(iframe);
}
// Use .setAttribute() to reliably navigate the iframe.
iframe.setAttribute("src", url);
}
visitPage(urls.pop());
Don't reload the hiddenWindow itself, or you will break lots of other code.
How can i Assert that the CSS for a page has successfully loaded and applied its styles in Watin 2.1?
After doing some research and writing up my answer, I stumbled upon this link that explains everything you need to know about CSS, when it is loaded and how you can check for it.
The link provided explains it so well, in fact, that I'm adding some quotes from it for future reference.
If you're curious, my answer was going to be #2 and a variation of #4.
When is a stylesheet really loaded?
...
With that out of the way, let's see what we have here.
// my callback function
// which relies on CSS being loaded function
CSSDone() {
alert('zOMG, CSS is done');
};
// load me some stylesheet
var url = "http://tools.w3clubs.com/pagr/1.sleep-1.css",
head = document.getElementsByTagName('head')[0],
link = document.createElement('link');
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
// MAGIC
// call CSSDone() when CSS arrives
head.appendChild(link);
Options for the magic part, sorted from nice-and-easy to ridiculous
listen to link.onload
listen to link.addEventListener('load')
listen to link.onreadystatechange
setTimeout and check for changes in document.styleSheets
setTimeout and check for changes in the styling of a specific element you create but style with the new CSS
5th option is too crazy and assumes you have control over the content of the CSS, so forget it. Plus it checks for current styles in a timeout meaning it will flush the reflow queue and can be potentially slow. The slower the CSS to arrive, the more reflows. So, really, forget it.
So how about implementing the magic?
// MAGIC
// #1
link.onload = function () {
CSSDone('onload listener');
};
// #2
if (link.addEventListener) {
link.addEventListener('load', function() {
CSSDone("DOM's load event");
}, false);
};
// #3
link.onreadystatechange = function() {
var state = link.readyState;
if (state === 'loaded' || state === 'complete') {
link.onreadystatechange = null;
CSSDone("onreadystatechange");
}
};
// #4
var cssnum = document.styleSheets.length;
var ti = setInterval(function() {
if (document.styleSheets.length > cssnum) {
// needs more work when you load a bunch of CSS files quickly
// e.g. loop from cssnum to the new length, looking
// for the document.styleSheets[n].href === url
// ...
// FF changes the length prematurely :(
CSSDone('listening to styleSheets.length change');
clearInterval(ti);
}
}, 10);
// MAGIC ends
There has been an update to the article lined to by #ShadowScripter. The new method purportedly works in all browsers, including FF.
var style = document.createElement('style');
style.textContent = '#import "' + url + '"';
var fi = setInterval(function() {
try {
style.sheet.cssRules; // <--- MAGIC: only populated when file is loaded
CSSDone('listening to #import-ed cssRules');
clearInterval(fi);
} catch (e){}
}, 10);
document.getElementsByTagName('head')[0].appendChild(style);
After page load you can verify the style on some of your elements something like this:
var style = browser.Div(Find.ByClass("class")).Style;
Assert.That(Style.Display, Is.StringContaining("none"));
Assert.That(Style.FontSize, Is.EqualTo("10px"));
And etc...
Since browser compatibility can vary, and new future browser standards subject to change, I would recommend a combination of the onload listener and adding CSS to the style sheet so you can listen for when the HTML elements z-index changes if you are using a single style sheet. Otherwise, use the function below with a new meta tag for each style.
Add the following to the CSS file that you are loading:
#*(insert a unique id for he current link tag)* {
z-index: 0
}
Add the following to your script:
function whencsslinkloads(csslink, whenload ){
var intervalID = setInterval(
function(){
if (getComputedStyle(csslink).zIndex !== '0') return;
clearInterval(intervalID);
csslink.onload = null;
whenload();
},
125 // check for if it has loaded 8 times a second
);
csslink.onload = function(){
clearInterval(intervalID);
csslink.onload = null;
whenload();
}
}
Example
index.html:
<!doctype html>
<html>
<head>
<link rel=stylesheet id="EpicStyleID" href="the_style.css" />
<script async href="script.js"></script>
</head>
<body>
CSS Loaded: <span id=result>no</span>
</body>
</html>
script.js:
function whencsslinkloads(csslink, whenload ){
var intervalID = setInterval(
function(){
if (getComputedStyle(csslink).zIndex !== '0') return;
clearInterval(intervalID);
csslink.onload = null;
whenload();
},
125 // check for if it has loaded 8 times a second
);
csslink.onload = function(){
clearInterval(intervalID);
csslink.onload = null;
whenload();
}
}
/*************************************/
whencsslinkloads(
document.getElementById('EpicStyleID'),
function(){
document.getElementById('result').innerHTML = '<font color=green></font>'
}
)
the_style.css
#EpicStyleID {
z-index: 0
}
PLEASE do not make your script load synchronously (without the async attribute) just so you can capture the link's onload event. There are better ways, like the method above.
what's the best approach to change the background of my website at each visit ?
1) write php code, loading a random css file containing the background property
2) write php code, generating different html (and including the background property directly into html code
3) something else ?
thanks
This can be done in your theme's page.tpl.php variable preprocessor. Store the random style in the $_SESSION array to re-use for all pages in the same user session. And append the markup to the $head variable used in the template.
YOURTHEME_preprocess_page(&$variables) {
$style = $_SESSION['YOURTHEME_background_style'];
if (!$style) {
$style = array();
//Generate your random CSS here
$style = "background-image: url('bg-". rand(0,10) .".png')";
$_SESSION['YOURTHEME_background_style'] = $style;
}
$variables['head'] .= '<style type="text/css">body {'. implode("\n", $style) .'}</style>';
}
Usually, $head is placed before $style in the page.tpl.php templaye, so CSS rules from any .css files will overrides your random rule. You may have to use !important in your random CSS to avoid this.
I would probably:
Use hook_user op login to detect the login and then store the background color code in the user object.
In your page template create an inline style for the background color that uses the value stored on the user object. For anonymous users don't do anything and have default defined in a style sheet.
Use a session cookie. Could be set either via js (client side) or something like php (server-side). Here's an example of a js-only solution:
<!doctype html>
<html><head><script>
var backgrounds=['foo.png', 'bar.png', 'hahah.png'];
function setBg () {
var currentBg=readCookie('which_bg');
if (!currentBg) {
currentBg=backgrounds[Math.random()*backgrounds.length|0];
createCookie('which_bg', currentBg);
}
document.body.style.backgroundImage='url('+currentBg+')';
}
// from http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script></head>
<body onload="setBg();">
...
</body></html>
To change the background image at each page load (not exactly "visit" though), you can use the Drupal module Dynamic Background. For Drupal 7, only the 7.x-2.x branch contains the option for cycling backgrounds randomly. You would install it with:
drush dl dynamic_background-7.x-2.x && drush en dynamic_background
The feature can also be added to the 7.x-1.x branch with a patch, and to the 6.x-1.x branch similarly.