Userscript breaking pages outside of domain - userscripts

Even though I have my userscript restricted to one domain, any site I visit that uses Jquery experiences all kinds of nasty issues when my script is active. Checking the error console in chrome reveals an identical error on all sites:
"Uncaught TypeError: Property '$' of object [object Window]"
What's causing this? My objective is to get my userscript running in noconflict mode on a site that uses both jquery and prototype. I didn't make the code above var = myFunction, so I don't know what about it is causing the problem I'm running into. Any suggestions?
// ==UserScript==
// #name Restore Dashboard Tags
// #namespace http://userstyles.org
// #description This script restores a user's tracked tag list to the sidebar on tumblr
// #author
// #homepage
// #history 1.0 first version
// #include http://www.tumblr.com/*
// #match http://www.tumblr.com/*
// ==/UserScript==
var jQuery, $ = null;
function addJQuery(callback) {
var p = null;
if(window.opera || window.navigator.vendor.match(/Google/)) {
var div = document.createElement("div");
div.setAttribute("onclick", "return window;");
p = div.onclick();
}
else {
p = Window;
}
jQuery = $ = p.jQuery.noConflict();
callback();
}
var myFunction = function() {
jQuery('div#right_column ul:first-child').after('<ul class="controls_section" id="tracked_tags"></ul>');
jQuery('div.tracked_tags a').each(function (i) {
var tagID = jQuery(this).attr("id");
var tagIDNumber = tagID.replace('tag_','');
var tagName = jQuery(this).attr("href");
var tagNameClean = tagName.replace('/tagged/','');
var tagContent ='';
tagContent += '<li><a href="'+tagName+'" id="'+tagID+'" class="tag">';
tagContent += '<div class="hide_overflow">'+tagNameClean+'</div>';
tagContent += '<span id="tag_unread_'+tagIDNumber+'" class="count" style=""></span></a></li>';
jQuery(tagContent).appendTo('div#right_column ul#tracked_tags');
});
};
var NewPosts = function(){
jQuery('div.tracked_tags > div').each(function (i) {
var thisIndex = jQuery(this).index();
if (jQuery(this).find('small').length){
var postCount = jQuery(this).find('small').text();
jQuery('div#right_column ul#tracked_tags li:eq('+thisIndex+')').find('.count').html(postCount.replace("new posts", "") );
}
});
setTimeout(NewPosts,30000);
}
addJQuery(myFunction);
addJQuery(NewPosts);

The problem has been solved! Someone on another site IDed the culprit as jQuery = $ = p.jQuery.noConflict();; since I wasn't loading my own copy of Jquery I didn't need noConflict, and its usage was hiding Jquery from the rest of the page.

Related

override pivot view _render function in custom module odoo 11

I want to override "_render: function ()" function from pivot_renderer.js file in web but not working in custom module. Here is the code i am implementing in my custom module:-
odoo.define('MY_CUSTOM_MODULE_NAME.renderer', function (require) {
"use strict";
var PivotRenderer = require('web.PivotRenderer');
var field_utils = require('web.field_utils');
var core = require('web.core');
var _t = core._t;
PivotRenderer.include({
init: function(parent, state, params) {
this._super.apply(this, arguments);
},
_render: function () {
if (!this._hasContent()) {
// display the nocontent helper
this.replaceElement(QWeb.render('PivotView.nodata'));
return this._super.apply(this, arguments);
}
if (!this.$el.is('table')) {
// coming from the no content helper, so the root element has to be
// re-rendered before rendering and appending its content
this.renderElement();
}
var $fragment = $(document.createDocumentFragment());
var $table = $('<table>').appendTo($fragment);
var $thead = $('<thead>').appendTo($table).addClass("CLASS_NAME");
var $tbody = $('<tbody>').appendTo($table);
var nbr_measures = this.state.measures.length;
var nbrCols = (this.state.mainColWidth === 1) ?
nbr_measures :
(this.state.mainColWidth + 1) * nbr_measures;
for (var i=0; i < nbrCols + 1; i++) {
$table.prepend($('<col>'));
}
this._renderHeaders($thead, this.state.headers);
this._renderRows($tbody, this.state.rows);
// todo: make sure the next line does something
$table.find('.o_pivot_header_cell_opened,.o_pivot_header_cell_closed').tooltip();
this.$el.html($table.contents());
return this._super.apply(this, arguments);
},
});
});
In the above, i want to add a class in the header for calling my custom css "var $thead = $('').appendTo($table).addClass("CLASS_NAME");" with this syntax but it is not reflecting in my custom module. Although, for testing, I have implemented same class in default web module and it is working fine. The issue is in custom module.
So how to solve this issue? Is there any other way for calling class or i am doing it in a wrong way?
var $thead = $('').addClass("CLASS_NAME").appendTo($table);
This will work in my case. You can try it.

Gulp-eslint throws errors on dynamically loaded JSs

I have a project structure like
There are approx 10 JS files in com. lab1 and lab2 has a config.json file which tells, out of 10 files which files to be concatenated and placed as app-min.js in dist/lab1 or dist/lab2.
In the gulp file I've created something like this.
var filesArr = [];
var labName;
// Player Task
gulp.task('player', function () {
return gulp.src(filesArr)
.pipe(eslint())
.pipe(babel())
.pipe(concat('app-min.js'))
.pipe(uglify({
compress: {
drop_console: true
}
}).on('error', gutil.log))
.pipe(gulp.dest('dist/' + labName));
});
// Clean
gulp.task('clean', function () {
if (readJson()) {
return del([
'dist/' + labName
]);
}
return null;
});
// Watch
gulp.task('watch', function () {
gulp.watch(filesArr, gulp.series('player'));
});
// Read Json and create JS Array
function readJson() {
// LAB STRUCTURE
var _n = prompt('Specify the LAB name. ');
labName = _n;
var _path = path.resolve('./src/' + _n);
var _exists = fs.existsSync(_path);
if (_exists) {
var _json = fs.readFileSync(path.resolve(_path + '/labstructure.json'), 'utf-8');
var _jObj = JSON.parse(_json).labObj.components;
for (var i = 0; i < _jObj.length; i++) {
var _jsName = 'src/com/component/' + _jObj[i].ref + '.js';
if (filesArr.indexOf(_jsName) === -1) {
filesArr.push(_jsName);
}
}
}
return _exists;
}
gulp.task('default', gulp.series('clean', 'player', 'watch'));
Here the filesArr looks like:
[ 'src/com/component/ColorActClass.js',
'src/com/component/PanelCompClass.js',
'src/com/component/ToggleCompClass.js',
'src/com/component/SliderCompClass.js',
'src/com/component/CheckBoxCompClass.js',
'src/com/component/ButtonCompClass.js',
'src/com/component/LabelCompClass.js',
'src/com/component/InputBoxClass.js',
'src/com/component/ColorMonitorClass.js',
'src/com/component/MsgBoxClass.js',
'src/com/component/ConfBoxClass.js',
'src/com/component/NumberPadClass.js',
'src/com/main/lib/webfontloader.js',
'src/com/main/lib/howler.core.min.js',
'src/com/main/PlayerClass.js',
'src/kl1001_color/BrainClass.js' ]
This works perfectly fine at the first place. But when any JS is modified then in watch player task throws eslint error on some files which are untouched. This doesn't happen always rather if watch is running for 10-20 mins then it throws error. Like this:
In this case CheckBoxCompClass.js is not the file which is modified, but still got the issue. On top of that, the semicolon is in place. If this file has issue then eslint should have thrown the error at the first place.
Please help.
Accidentally, my NVM was set to an older version. Solved the issue after updating the NVM and by setting the current NVM version to the latest one.

How to apply delay in JSZip API to load?

How to apply delay in JSZip API ? I want to zip multiple file. but I want to add some delay between transferring the files from webserver. How to add delay in below code?
This is for browser and deploying binaries inside the device.
$scope.download = function () {
var urls = ["/FILES/AlertLog.txt",
"/FILES/AuditLog.txt",
"/FILES/TotLog.txt",
"/FILES/Historian.csv",
"/FILES/History2.csv",
"/FILES/Factory.cfg",
"/FILES/SLog.txt",
"/FILES/se.dump",
"/FILES/AssertLog.txt",
"/FILES/History2.csv",
"/FILES/History3.csv",
"/FILES/History4.csv"
];
compress_files(urls);
}
function compress_files(urls) {
var zip = new JSZip();
var deferreds = [];
for (var i = 0; i < urls.length; i++) {
$timeout(function(){ deferreds.push(addToZip(zip, urls[i], i));
},200);// issue to deferreds variable =>undefined
$.when.apply(window, deferreds).done(generateZip);
}
function addToZip(zip, url, i) {
var deferred = $.Deferred();
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
deferred.resolve(zip);
}
else {
var arr=url.split("/");
zip.file(arr[2], data, { binary: true });
deferred.resolve(zip);
}
});
return deferred;
}
add some delay of milliseconds between transferring the files from the webserver.
I am trying to download the individual file by giving some delay. It fixed my problem
function downloadAll(files){
if(files.length == 0) return;
file = files.pop();
var theAnchor = $('<a />')
.attr('href', file[1])
.attr('download',file[0])
// Firefox does not fires click if the link is outside
// the DOM
.appendTo('body');
theAnchor[0].click();
theAnchor.remove();
downloadAll(files); }
function downloadAll(files){
if(files.length == 0) return;
file = files.pop();
var theAnchor = $('<a />')
.attr('href', file[1])
.attr('download',file[0])
// Firefox does not fires click if the link is outside
// the DOM
.appendTo('body');
theAnchor[0].click();
theAnchor.remove();
downloadAll(files);
}
$('a.download-csv').on('click', function(){
downloadAll([
['file1.csv', 'data:text/csv;charset=utf8,'+
encodeURIComponent('my,csv,file\and,so,on')],
['file2.txt', 'data:text/plain;charset=utf8,'+
encodeURIComponent('this script can do what I need.')],
['file3.js', 'data:text/javascriptcharset=utf8,'+
encodeURIComponent('alert(\'You can donate me your house if you like this script :-) \')')]
]);
});

Why this component doesnt work if I use: polymer init app-drawer-template

Hi Im just a rookie with polymer, I hope this question doesnt sound stupid for you :(
I am triying to make a image gallery and I am using this idea: From this page
<dom-module id="simple-gallery" >
<script>
HTMLImports.whenReady(function () {
(function() {
var current_index = 0;
var image_length = 0;
Polymer({
is: "simple-gallery",
ready: function() {
var images = Polymer.dom(this).querySelectorAll('img');
var container = this.$.links;
for (var img in images) {
images[img].addEventListener('click',this.load_popup);
container.appendChild(images[img]);
}
},
load_popup: function(e, detail, sender) {
e.preventDefault();
var links = document.getElementById('links');
image_length = links.getElementsByTagName('img').length;
var image_url = e.target.getAttribute('data-original');
var modalbody = document.getElementsByClassName("modal-body")[0];
var modal_img = modalbody.getElementsByTagName('img')[0];
modal_img.setAttribute("src",image_url);
var modal = document.getElementsByClassName("modal")[0];
modal.style.display = 'block';
current_index = parseInt(e.target.getAttribute('data-index').replace("s",""));
return false;
},
next: function () {
current_index = current_index + 1;
if(current_index == (image_length + 1) ){
current_index = 1;
}
var current_image = document.querySelectorAll("[data-index='s"+current_index+"']");
image_url = current_image[0].getAttribute('data-original');
var modalbody = document.getElementsByClassName("modal-body")[0];
var modal_img = modalbody.getElementsByTagName('img')[0];
modal_img.setAttribute("src",image_url);
},
prev: function () {
current_index = current_index - 1;
if(current_index == 0 ){
current_index = image_length;
}
var current_image = document.querySelectorAll("[data-index='s"+current_index+"']");
image_url = current_image[0].getAttribute('data-original');
var modalbody = document.getElementsByClassName("modal-body")[0];
var modal_img = modalbody.getElementsByTagName('img')[0];
modal_img.setAttribute("src",image_url);
},
close: function () {
var modal = document.getElementsByClassName("modal")[0];
modal.style.display = "none";
},
});
})();
});
</script>
<template>
I realy dont understand why this code works fine if I use it as in the example, but if I create a proyect with: polymer init app-drawer-template and I use this as an element wich is called from one of the views I have an error :(
Uncaught ReferenceError: HTMLImports is not defined(anonymous function) # simple-gallery.html:91
Surely I am not understanding well something but I dont know why, hope somebody has the time to give me a brief explanation :(
thanks a lot for your time.
I had the same issue so I have added following include in my main html:
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
Which worked for me.

WMD editor freezes Internet Explorer 7 for 3 seconds on load

I am using the WMD editor's original code (not the Stack Overflow version) since I need multiple of them on the same page and Stack Overflow's version makes heavy use of element IDs internally since they aren't going to be having more than one editor instance per page.
The code runs fine in Firefox 3.5, etc. However, when I run it in Internet Explorer 8 (in Internet Explorer 7 compatibility mode), it freezes the whole browser for about 3 sec. before a new instance shows up. I tried profiling it with Internet Explorer's development tools, and it seems that the getWidth() function on line 520 of the minified version of the code is taking up all the time. However, when I tried to hard-code the return (since it was always returning the same thing), the bottleneck shifted to the getHeight() function.
I am attaching the code I am using to convert it to a jQuery plugin.
jQuery.fn.wmd = function(params) {
function createInstance(container, params) {
/* Make sure WMD has finished loading */
if (!Attacklab || !Attacklab.wmd) {
alert("WMD hasn't finished loading!");
return;
}
var defaultParams = {
width : "600px",
rows : 6,
autogrow : false,
preview : false,
previewDivClassName: "wmd-preview-div"
};
if (typeof(params) == "undefined") {
var params = defaultParams;
}
else {
var params = jQuery.extend({}, defaultParams, params);
}
/* Build the DOM elements */
var textarea = document.createElement("textarea");
textarea.style.width = params.width;
textarea.rows = params.rows;
jQuery(container).append(textarea);
var previewDiv = document.createElement("div");
if (params.preview) {
jQuery(previewDiv).addClass(params.previewDivClassName);
jQuery(container).append(previewDiv);
}
/* Build the preview manager */
var panes = {input:textarea, preview:previewDiv, output:null};
var previewManager = new Attacklab.wmd.previewManager(panes);
/* Build the editor and tell it to refresh the preview after commands */
var editor = new Attacklab.wmd.editor(textarea,previewManager.refresh);
/* Save everything so we can destroy it all later */
var wmdInstance = {ta:textarea, div:previewDiv, ed:editor, pm:previewManager};
var wmdInstanceId = $(container).attr('postID');
wmdInstanceProcs.add(wmdInstanceId, wmdInstance);
if (params.autogrow) {
// $(textarea).autogrow();
}
};
if (jQuery(this).html().length > 0) {
var wmdInstanceId = jQuery(this).attr('postID');
var inst = wmdInstanceProcs.get(wmdInstanceId);
jQuery(inst.ta).show();
}
else {
createInstance(this, params);
}
}
jQuery.fn.unwmd = function(params) {
var wmdInstanceId = $(this).attr('postID');
var inst = wmdInstanceProcs.get(wmdInstanceId);
if (inst != null) {
jQuery(inst.ta).hide();
}
}
wmdInstanceProcs = function() {
var wmdInstances = { };
var getProc = function(wmdInstanceId) {
var inst = wmdInstances[wmdInstanceId];
if (typeof(inst) != "undefined") {
return inst;
}
else {
return null;
}
};
var addProc = function(wmdInstanceId, wmdInstance) {
wmdInstances[wmdInstanceId] = wmdInstance;
};
return {
add: addProc,
get: getProc
};
}();
Any help would be much appreciated.
Maybe the freeze in load time is due to IE 7 rendering the JavaScript. Firefox may be faster at rendering and so it makes IE appear to freeze.

Resources