Probe clientCaps with javascript - javascript

I'm trying to probe the clientCaps object in Javascript (I'm not very familiar with behaviours in MSIE). But not having much luck.
Due to other constraints, I can't really modify the HTML of the page and hence trying to add an element dynamically. The code I'm using is shown below - I keep getting exceptions (object doesn't support this property or method). Any ideas what I'm doing wrong?
var out="";
try {
var b = document.getElementsByTagName("body")[0];
var s = document.createElement("div");
// attempt 1 - exception
// s.id="oClientCaps";
// s.style.behaviour="url('#default#clientCaps')";
//
// attempt 2 - exception
// s.innerHTML='<a ID="oClientCaps" style="behavior:url(#default#clientcaps)"></a>';
//
// attempt 3 - exception
s.id="oClientCaps";
s.addBehavior ("#default#clientCaps");
b.appendChild(s);
var clids = Array('{7790769C-0471-11D2-AF11-00C04FA35D02}', // address bk
...
'{08B0E5C0-4FCB-11CF-AAA5-00401C608500}'); // MS VM
for(i=0;i<clids.length;i++) {
if(oClientCaps.isComponentInstalled(clids[i],"ComponentID")){
out+=clsids[i]
+ oClientCaps.getComponentVersion(clids[i],"ComponentID")
+ '; ';
} else {
out+='N; '
}
}
} catch (e) {
out+="clientCaps failed";
}
return out;
TIA

Found that the following works (although I'm not sure why the other methods failed):
var b = document.getElementsByTagName("body")[0];
var s = document.createElement("div");
s.innerHTML="<div style='behavior:url(#default#clientCaps)' ID='oClientCaps' ></div>";
b.appendChild(s);
(etc)

Related

Call variable value in another .js file

I have 2 soy.js and lib-dialogs.js files.
I need to make lib-dialogs pass the value of the lineCount variable to soy.js.
I was able to do this with localStorage but because it saves in a cookie it does not update the values correctly.
In lib-dialogs there is a function called BlocklyDialogs.congratulations that calls the necessary data.
FIle:lib-dialogs.js
BlocklyDialogs.congratulations = function() {
// Add the user's code.
if (BlocklyGames.workspace) {
var linesText = document.getElementById('dialogLinesText');
linesText.textContent = '';
// Line produces warning when compiling Puzzle since there is no JavaScript
// generator. But this function is never called in Puzzle, so no matter.
var code = Blockly.JavaScript.workspaceToCode(BlocklyGames.workspace);
code = BlocklyInterface.stripCode(code);
var noComments = code.replace(/\/\/[^\n]*/g, ''); // Inline comments.
noComments = noComments.replace(/\/\*.*\*\//g, ''); /* Block comments. */
noComments = noComments.replace(/[ \t]+\n/g, '\n'); // Trailing spaces.
noComments = noComments.replace(/\n+/g, '\n'); // Blank lines.
noComments = noComments.trim();
var lineCount = noComments.split('\n').length;
var pre = document.getElementById('containerCode');
pre.textContent = code;
if (typeof prettyPrintOne == 'function') {
code = pre.innerHTML;
code = prettyPrintOne(code, 'js');
pre.innerHTML = code;
}
if (lineCount == 1) {
var text = BlocklyGames.getMsg('Games_linesOfCode1');
} else {
var text = BlocklyGames.getMsg('Games_linesOfCode2')
.replace('%1', String(lineCount));
}
linesText.appendChild(document.createTextNode(text));
}
FIle:soy.js
example "var count = BlocklyDialogs.congratulations(lineCount);"
In soy.js I need to receive the values of lineCount. I've already managed to do this using localStorage but I needed to do something more direct.
In testing I verified that the problem is in the lineCount variable because it is not passing a value to any variable even within the file itself.
I created a variable outside the blocklyDialogs.congratulations function and entered a value of 5.
I called the variable in the soy.js file and got it normally.
I need to make the lineCount pass its value.
You can use event driven programming, pub-sub model.
class EventManager {
constructor(...listeners) {
this.listeners = listeners;
}
register(fn) {
const id = this.listeners.push(fn);
return () => {
this.listeners.splice(id - 1, 1);
};
}
emit(data) {
this.listeners.forEach(fn => fn(data));
}
}
const pushEvents = new EventManager();
// JS 1
const unsubscribe1 = pushEvents.register(x => {
console.log("event:", x);
});
pushEvents.register(x => {
console.log("event:", x);
});
// JS 2
pushEvents.emit("Tets data");
//Output
// event: Tets data
// event: Tets data
unsubscribe1();
pushEvents.emit("Tets data2");
//Output
// event: Tets data2
.as-console-row {color: red!important}

ViewerJS str.replace how to make it work

I was taking a look at ViewerJS and seems like a good fit the only problem i found was title came out with %20 instead of space. I know why, but I cannot figure out how to fix it.
so it looks like this code gets worked first. how would i fix it in here to make it display with no %20.
function getPDFFileNameFromURL(url) {
var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
// SCHEME HOST 1.PATH 2.QUERY 3.REF
// Pattern to get last matching NAME.pdf
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) ||
reFilename.exec(splitURI[2]) ||
reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
// URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
try {
suggestedFilename =
reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch(e) { // Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf"
}
}
}
return suggestedFilename || 'document.pdf';
}
var x = 'Some%20string%20with%20spaces';
x = x.replace(/%20/g, ' ');
console.log(x);

Uncaught TypeError: object is not a function after second refresh

At the moment I'm facing a javascript problem. This is the javascript code:
$(document).ready(function() {
/*
createNewTodo("_OPDRACHT_", "_PRIO_", "_DONE_");
_OPDRACHT_ = wat er gedaan met worden.
_PRIO_ = prioriteit 1-5 (1 is hoogste, 5 is laagste)
_DONE_ = uitgevoerd 1-2 (1 is nee, 2 is ja
*/
function todo(opdracht,prio,done) {
this.opdracht = opdracht;
this.prio = prio;
this.done = done;
}
function createNewTodo(opdracht,prio,done) {
var createdTodo = new todo(opdracht,prio,done);
if ( localStorage.todoCount == undefined ) {
localStorage.setItem('todoCount', 0)
}
var todoSize = parseInt(localStorage.todoCount) + 1;
commitToStorage(todoSize,createdTodo);
}
function addList(){
var val = $('#name').val();
var tjap = createNewTodo(val,"1","1");
}
function commitToStorage(objectCount,newObject) {
var item = + objectCount;
localStorage.setItem('todoCount', objectCount);
localStorage.setItem(item, JSON.stringify(newObject));
}
var todoCount = localStorage.getItem('todoCount');
for (i=1;i<=todoCount;i++)
{
var number = parseInt(i) + 1;
var todo = jQuery.parseJSON(localStorage.getItem(+ i));
createMarkup(todo);
}
function createMarkup(todo) {
$('ul#items').append(
"<li>" +
todo.opdracht + " " +
"</li>"
);
}
$('#add-btn').click(addList);
});
When I click on the add-btn it will insert a item in localstorage with a array of values. Everything is working fine until I refresh the page. At the first time I can add as many items in localstorage without a problem but when I try to add items after refreshing the page I get the following error: Uncaught TypeError: object is not a function. Been searching a lot on the internet but could't find a appropriate solution for this. Anyone that can help me out and push me in the right direction? Thanks in advance.
There is no separated local scope inside for loop so you are assigning an object to your variable called todo that was previously declared as a function instead of creating a new local variable with the same name to store your todo data.
You can read more about this particular topic and most of the features and 'pitfalls' of the language on http://bonsaiden.github.io/JavaScript-Garden/#function.scopes . I would strongly suggest you to read the whole page, it will save you a lot of time in the future.

Loop through Iframe using Javascript

I have create one automate program, for that I require to iterate through every frame document and set some input.
I iterate it with below function, which is working fine, but in below URL it gave me Access Denied error.
http://usacarhire.com/
Code I am using to iterate through every frame and Iframe.
var i = new Array;
var t = '';
var IFrameDoc;
function GetAllFrame(a, n)
{
t = '';
try {
for (i[n] = 0; i[n] < a.length; i[n]++)
{try{
var oIframe = a[i[n]];
IFrameDoc = oIframe.document;
alert(IFrameDoc.body.outerHTML);
}
catch (e) {
alert("Internal Error" + e.message + " - " + a[i[n]].frames.length);
}
if (a[i[n]].frames.length) t += GetAllFrame(a[i[n]].frames, n + 1);
}
}
catch (e) {
alert("External Error" + e.message);
}
return t;}
If the other iFrames aren't yours then it can not be solved, you can not override the cross origin policy.
If you do own both of them what you can do is use HTML5's postMessage API to "talk" between the iFrame and the parent window, but I don't believe that is what you want.
If you do, leave a comment and I will edit my answer.

How to check table for new content, and then update browser tab title?

I am working on a way to flash a browser tab when a new message appears in a table. I have the flashing of the tab part working, my only problem is that I can't seem to get it to flash when a message is received (which is the whole point of my exercise :) )
The newMessage() function is working fine, I just can't seem to get the notification() function to work.
My code is as follows:
function newMessage()
{
var oldTitle = "Your Page";
var msg = "New Message";
var timeout = setInterval(function()
{
document.title = document.title == msg ? '' : msg;
}, 1000);
window.onmousemove = function() {
clearInterval(timeout);
document.title = oldTitle;
window.onmousemove = null;
};
}
function notification()
{
var index = 2;
var content = document.getElementById('refreshMessages').childNodes[index];
var content = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
var knownContent = content.toString();
updater.start();
updater2.start();
var newContent = document.getElementById('refreshMessages').childNodes[index];
var newContent = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
if(knownContent != newContent.toString())
{
newMessage();
knownContent = newContent;
}
else if(knownContent = newContent.toString())
{
alert("No need to flash title.");
}
}
notification();
In the notification() function, I am trying to call the newMessage() function by comparing the strings at the appropiate cell in the table.
I put the alert() into the else if just to see if it would be called, but it does not happen. update.start() and update2.start() are carried out however, as I can see the messages appearing in the table.
I would be happier to use JavaScript but I am open to jQuery also.
My JavaScript is very very rusty so excuse me if I have made any silly mistakes!
Thanks,
Chuck
You have several mistakes in function notification(), see my comments:
function notification()
{
var index = 2;
//Why are you assigning value to "content" for twice?
var content = document.getElementById('refreshMessages').childNodes[index];
/*
* function getElementByTagName is undefined, should be getElementsByTagName,
* 's' is missing. And [1] means the second one not the first one, make sure
* that's exactly what you want.
*/
var content = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
/*
* content is a tr dom object, content.toString() is something like "[object]".
* If you want to get content inside a cell, you should use cell.innerHTML.
* e.g. A table:
* <table id="refreshMessages">
* <tr><td>Hello world</td></tr>
* </table>
* var table = document.getElementById('refreshMessages');
* var firstTr = table.getElementsByTagName("tr")[0];
* var firstTd = firstTr.getElementsByTagName("td")[0];
* alert(firstTd.innerHTML); //alerts "Hello world"
*/
var knownContent = content.toString();
//I doubt these functions really get invoked cuz there's javascript error above.
updater.start();
updater2.start();
//assigning twice, "getElementByTagName" is missing "s"
var newContent = document.getElementById('refreshMessages').childNodes[index];
var newContent = document.getElementById('refreshMessages').getElementByTagName("tr")[1];
//Remove toString(), use innerHTML i metioned above.
if(knownContent != newContent.toString())
{
newMessage();
knownContent = newContent;
}
//You miss an "=" here, to judge a equals b, you should use "=="
else if(knownContent = newContent.toString())
{
alert("No need to flash title.");
}
}

Categories