Rectangle 27 15

Functions don't exist as part of the DOM; instead, they exist within an execution environment that includes the DOM. Content scripts (including scripts run with executeScript) and actual web pages share the same DOM, but have separate execution environments. So calling window.alert = function() {} only rewrites window.alert within your content script's execution environment, not in the actual page's one.

The typical way to reach the execution environment of the actual page is to inject a <script> tag into the DOM. This can be done in several ways. One method is to white-list a script in web_accessible_resource, and insert the <script> element referring to this script in the document. The required absolute URL can be obtained via chrome.extension.getURL.

var s = document.createElement("script");
s.src = chrome.extension.getURL("script_in_extension.js");
(document.head||document.documentElement).appendChild(s);

Make sure that the script is configured to "run_at": "document_start", so that the overwrite takes place before any of the page's functions are loaded.

Note: Your action can easily be undone by the page:

window.alert = function(){ /*...*/ }; // Your overwrite
delete window.alert;                  // Run from the page/console/...
window.alert('Test?');                // Displays alert box.

If it's critical that the overwritten function cannot be removed, use Object.defineProperty to define an immutable method. For more details, see Stop a function from execute with Chrome extension.

@RobW defineProperty is a very good note (but should it read "replace the property", or am I not quite following you?). I didn't mention the run_at property since they OP only asked about using executeScript, but it's definitely useful and relevant in almost all cases. Looks good, thanks.

@RobW @apsillers, Re "..overwrite.."; you'll also need to async=false if you're using src=. In any case, I've got little faith that its guaranteed to run at the start, even while the docs write that its before any other script is run. Does someone have a link to that portion of source code? Also, aside from <manifest executescript document_start> there's <onCommitted executescript document_start>.

ftp://speedtest.tele2.net
www.w3fools.com
https://en.wikipedia.org/wiki/Main_Page

google chrome - Is it possible to inject a javascript code that OVERRI...

google-chrome google-chrome-extension
Rectangle 27 3

When the UpdatePanel updates the DOM and rewrites script blocks into the DOM, they are not re-executed. You need to get on the client-side event that fires after the UpdatePanel is finished and re-execute your JS blocks:

<script type="text/javascript">
    function handleEndRequest(sender, args)
    {
        var panel = document.getElementById(sender._postBackSettings.panelID);
        var scripts = panel.getElementsByTagName('script');
        for(var i=0;i<scripts.length;i++) {
            eval(scripts[i].innerHTML);
        }
    }

    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(handleEndRequest);
</script>

I just wondering where should I put this function is just before my function or on the header. sorry, I am new to javascript, can someone give me more details, thanks

and I have been put this function in both header and in my updatepanel2, but it still doesn't work, want more details.

@Dirk put the whole thing at the bottom of the page, after </body>

@Rex M, I have been put this code just after </body>, which cause my label1 doesn't update any more, I think it's because I have the code<script type="text/javascript">var prm = Sys.WebForms.PageRequestManager.getInstance(); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(alert("1")); setTimeout("Update()", 1000);function Update() { prm._doPostBack('UpdatePanel1', '');setTimeout("Update()", 1000); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(displayVideo());}</script> which is used for updatepanel1

@Dirk your add_endRequest(functionName()); is an error. You are calling alert, which returns nothing. You need to pass a reference to the function you want to call - not call it. Putting () at the end invokes it right then and there.

c# - How can I recall a javascript function after updatepanel update -...

javascript c# updatepanel
Rectangle 27 3

When the UpdatePanel updates the DOM and rewrites script blocks into the DOM, they are not re-executed. You need to get on the client-side event that fires after the UpdatePanel is finished and re-execute your JS blocks:

<script type="text/javascript">
    function handleEndRequest(sender, args)
    {
        var panel = document.getElementById(sender._postBackSettings.panelID);
        var scripts = panel.getElementsByTagName('script');
        for(var i=0;i<scripts.length;i++) {
            eval(scripts[i].innerHTML);
        }
    }

    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(handleEndRequest);
</script>

I just wondering where should I put this function is just before my function or on the header. sorry, I am new to javascript, can someone give me more details, thanks

and I have been put this function in both header and in my updatepanel2, but it still doesn't work, want more details.

@Dirk put the whole thing at the bottom of the page, after </body>

@Rex M, I have been put this code just after </body>, which cause my label1 doesn't update any more, I think it's because I have the code<script type="text/javascript">var prm = Sys.WebForms.PageRequestManager.getInstance(); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(alert("1")); setTimeout("Update()", 1000);function Update() { prm._doPostBack('UpdatePanel1', '');setTimeout("Update()", 1000); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(displayVideo());}</script> which is used for updatepanel1

@Dirk your add_endRequest(functionName()); is an error. You are calling alert, which returns nothing. You need to pass a reference to the function you want to call - not call it. Putting () at the end invokes it right then and there.

c# - How can I recall a javascript function after updatepanel update -...

javascript c# updatepanel
Rectangle 27 2

As others have pointed out, the DOM API is quite verbose for such simple operations. If you use something like jOOX to wrap the DOM API, you could write any of the following:

// Find the element using XPath, and insert XML text after it
$(document).xpath("//sequence/assign[@name='Assign1']")
           .after("<newtype name=\"NewNode\"/>");

// Find the element using jOOX API, and insert an object after it
$(document).find("sequence")
           .find("assign")
           .filter(attr("name", "Assign1"))
           .after($("newtype").attr("name", "NewNode"));

Note how the API resembles that of jQuery.

xml - Java DOM - Inserting an element, after another - Stack Overflow

java xml dom
Rectangle 27 3

I'll attempt to answer some of these for you. You only really want 1 document ready call per page, but it doesn't matter if you have multiples. Whatever is contained within them is going to be the code that executes once the DOM has been loaded into the browser. Rails won't do anything magical with the javascript, it will stay the same as what you write in your files. Rails won't compile the javascript code in a funky way, for production environments it may minify it, but the actual code will remain mostly the same. This is executed by the browser - not the server.

You are not instantiating 2 instances as jQuery is only loaded once, then referenced. The $(document).ready() call is just a function essentially, nothing more.

The model-specific jquery files can be used in conjunction with Ajax in a rails app. So you can have files like 'create.js.erb' which is actually a javascript file you can pass rails actions into. If you want to fire some specific code after a create/delete post then you can use files like this to do that, you just have to respond the javascript in your rails controller - but this is going a bit deeper that you mean to by the looks of your question above.

The main thing to remember is jquery is just javascript and javascript gets run by the browser - on the front end without any dynamic integration, is will always run on the client side and jquery is fantastic mainly for DOM manipulation.

How to properly work with jQuery in Rails 3.1 asset pipeline? - Stack ...

jquery ruby-on-rails ruby-on-rails-3.1 asset-pipeline
Rectangle 27 6

JSON (JavaScript Object Notation) is not designed for serializing DOM Nodes, you'll need to pull out the stuff you want by yourself and write it to an object, and then re-create the DOM Nodes from that if you need.

TypeError: Converting circular structure to JSON

javascript - JSON serialize a DOM element - Stack Overflow

javascript json
Rectangle 27 16

AFAIK, all extensions to the JS language (not the DOM) by browser vendors have at least been pushed for standard adoptioneven if the standards process has failed to achieve that. hasOwnProperty/workarounds: double-edged sword. To force the "simplicity", we lose a lot of power and flexibility. That complaint always pisses me off. Write your loops right (and check your object members right too)!

What are five things you hate about your favorite language? - Stack Ov...

programming-languages language-agnostic
Rectangle 27 16

AFAIK, all extensions to the JS language (not the DOM) by browser vendors have at least been pushed for standard adoptioneven if the standards process has failed to achieve that. hasOwnProperty/workarounds: double-edged sword. To force the "simplicity", we lose a lot of power and flexibility. That complaint always pisses me off. Write your loops right (and check your object members right too)!

What are five things you hate about your favorite language? - Stack Ov...

programming-languages language-agnostic
Rectangle 27 16

AFAIK, all extensions to the JS language (not the DOM) by browser vendors have at least been pushed for standard adoptioneven if the standards process has failed to achieve that. hasOwnProperty/workarounds: double-edged sword. To force the "simplicity", we lose a lot of power and flexibility. That complaint always pisses me off. Write your loops right (and check your object members right too)!

What are five things you hate about your favorite language? - Stack Ov...

programming-languages language-agnostic
Rectangle 27 6

With canvas you don't have to deal with the DOM, which leads to faster and easier to write code. SVG is a mess as a specification, too...

html5 canvas element and svg - Stack Overflow

html5 svg
Rectangle 27 2

as everybody suggested. document.write will clear everything from the DOM. the best way to write this would be to have a DIV in your HTML and set that div in your javascript code.

<div id="page_message" style="display: none;"></div>
<div class="countdown_out">
<div id="countdown_title">NFL Season Opener Countdown</div>
<div class="countdown_position">
    <div class="countdownBox">
        <div class="countdown_time_category">Days</div>
        <div id="daysBox" class="countdown_time"></div>
    </div>
    <div class="countdownBox">
        <div class="countdown_time_category">Hours</div>
        <div id="hoursBox" class="countdown_time"></div>
    </div>
    <div class="countdownBox">
        <div class="countdown_time_category">Minutes</div>
        <div id="minsBox" class="countdown_time"></div>
    </div>
    <div class="countdownBox">
        <div class="countdown_time_category">Seconds</div>
        <div id="secsBox" class="countdown_time"></div>
    </div>
</div>
<script type="text/javascript">
    function cdtd() {
        var nflSeason = new Date("September 10, 2015 08:30:00");
        var now = new Date();
        var timeDiff = nflSeason.getTime() - now.getTime();
        if (timeDiff < 0) {
            clearTimeout(timer);
            document.getElementById("page_message").innerHTML = 'The NFL Season is here!!';
            document.getElementById("page_message").style.display = 'inline';

            //Run any code needed for countdown completion here.
        }

        var seconds = Math.floor(timeDiff / 1000);
        var minutes = Math.floor(seconds / 60);
        var hours = Math.floor(minutes / 60);
        var days = Math.floor(hours / 24);
        hours %= 24;
        minutes %= 60;
        seconds %= 60;

        document.getElementById("daysBox").innerHTML = days;
        document.getElementById("hoursBox").innerHTML = hours;
        document.getElementById("minsBox").innerHTML = minutes;
        document.getElementById("secsBox").innerHTML = seconds;

        var timer = setTimeout('cdtd()', 1000);
    }
</script>

javascript - document.write is killing page - Stack Overflow

javascript jquery html timer
Rectangle 27 359

Get or Set an element's title property with jQuery (v1.6+)

Before we write any code, let's discuss the difference between attributes and properties. Attributes are the settings you apply to elements in your HTML markup; the browser then parses the markup and creates DOM objects of various types that contain properties initialized with the values of the attributes. On DOM objects, such as a simple HTMLElement, you almost always want to be working with its properties, not its attributes collection.

The current best practice is to avoid working with attributes unless they are custom or there is no equivalent property to supplement it. Since title does indeed exist as a read/write property on many HTMLElements, we should take advantage of it.

You can read more about the difference between attributes and properties here or here.

With this in mind, let's manipulate that title...

Since title is a public property, you can set it on any DOM element that supports it with plain JavaScript:

document.getElementById('yourElementId').title = 'your new title';
var elementTitle = document.getElementById('yourElementId').title;

This will be the fastest way of changing the title if you're an optimization nut, but since you wanted jQuery involved:

jQuery introduced a new method in v1.6 to get and set properties. To set the title property on an element, use:

$('#yourElementId').prop('title', 'your new title');

If you'd like to retrieve the title, omit the second parameter and capture the return value:

prop()

If you really don't want to use properties, or you're using a version of jQuery prior to v1.6, then you should read on:

You can change the title attribute with the following code:

$('#yourElementId').attr('title', 'your new title');
var elementTitle = $('#yourElementId').attr('title');
attr()

Thanks a ton! Very helpful

If this isn't a well constructed answer, none are. AND it is as accurate as it is well constructed. +1... (oh, and also your name is awesome, because it is mine :) even spelled the same!)

@VoidKing: I tend to revisit and make current answers that become popular (of which I only have a few). I try to provide everything that I would hope to find if I were researching or posting a question. I'm glad you found it!

@Cory Well, to be honest as I was looking for something else (it was a long shot, but was looking if there was any way to style the default HTML title box). I didn't find what I was looking for, but really admired the effort you put into this answer (you showed resources, pure .js and jQuery, etc.). Anyway, nice answer!

@VoidKing: This is probably the wrong place to answer, but if you're talking about the default tooltips that appear when you hover over items with alt or title attributes, then perhaps this answer will give you some insight.

forms - How to change an element's title attribute using jQuery - Stac...

jquery forms attributes
Rectangle 27 359

Get or Set an element's title property with jQuery (v1.6+)

Before we write any code, let's discuss the difference between attributes and properties. Attributes are the settings you apply to elements in your HTML markup; the browser then parses the markup and creates DOM objects of various types that contain properties initialized with the values of the attributes. On DOM objects, such as a simple HTMLElement, you almost always want to be working with its properties, not its attributes collection.

The current best practice is to avoid working with attributes unless they are custom or there is no equivalent property to supplement it. Since title does indeed exist as a read/write property on many HTMLElements, we should take advantage of it.

You can read more about the difference between attributes and properties here or here.

With this in mind, let's manipulate that title...

Since title is a public property, you can set it on any DOM element that supports it with plain JavaScript:

document.getElementById('yourElementId').title = 'your new title';
var elementTitle = document.getElementById('yourElementId').title;

This will be the fastest way of changing the title if you're an optimization nut, but since you wanted jQuery involved:

jQuery introduced a new method in v1.6 to get and set properties. To set the title property on an element, use:

$('#yourElementId').prop('title', 'your new title');

If you'd like to retrieve the title, omit the second parameter and capture the return value:

prop()

If you really don't want to use properties, or you're using a version of jQuery prior to v1.6, then you should read on:

You can change the title attribute with the following code:

$('#yourElementId').attr('title', 'your new title');
var elementTitle = $('#yourElementId').attr('title');
attr()

Thanks a ton! Very helpful

If this isn't a well constructed answer, none are. AND it is as accurate as it is well constructed. +1... (oh, and also your name is awesome, because it is mine :) even spelled the same!)

@VoidKing: I tend to revisit and make current answers that become popular (of which I only have a few). I try to provide everything that I would hope to find if I were researching or posting a question. I'm glad you found it!

@Cory Well, to be honest as I was looking for something else (it was a long shot, but was looking if there was any way to style the default HTML title box). I didn't find what I was looking for, but really admired the effort you put into this answer (you showed resources, pure .js and jQuery, etc.). Anyway, nice answer!

@VoidKing: This is probably the wrong place to answer, but if you're talking about the default tooltips that appear when you hover over items with alt or title attributes, then perhaps this answer will give you some insight.

forms - How to change an element's title attribute using jQuery - Stac...

jquery forms attributes
Rectangle 27 13

Popups live in the same process (the extension process) as the background page, and one page can get the DOM Window of the other. A popup gets the background page by calling chrome.extension.getBackgroundPage(). So every time you open the popup, just read and write to some variable on the background page, for example chrome.extension.getBackgroundPage().enteredData = "value";.

localStorage['enteredData'] = "value"

This only works for saving javascript. There's no way to maintain the DOM state of an actual html page between popup open/closes.

javascript - Background Page in popup- chrome extension - Stack Overfl...

javascript google-chrome-extension
Rectangle 27 2

You need to inject the script at runtime (as opposed to doing it from the content script). From the injected script use either messages to pass it to the extension, or (easier) write what you need in a DOM element and read it from the DOM (but changing the dom might break the original page) In the official samples shows how to inject the script by writting a tag.

I know this is a dup of the pointed gmail question but that question has a title that makes it hard to know its about injected scripts.

How can I access a window variable from a chrome extension? - Stack Ov...

google-chrome google-chrome-extension
Rectangle 27 1

Try to write you code in $(document).ready() so that you DOM is ready to use, otherwise it may not work. You have to add:

$(function(){
    //Your Js code
});
$(function(){
var $list = $('li');
$list.click(function() {
  alert("working");
  });
});

javascript - Basic jQuery commands not working - Stack Overflow

javascript jquery
Rectangle 27 1

It's rather a shame that it has become so common to speak of tree-building libraries such as DOM or JDOM as "parsers". Really there are two bit of software here: a parser (which reads the sequence of characters in the source, analyses it, and emits a sequence of events representing syntactic units such as start and end tags), and a tree builder, which takes the sequence of events from a parser and builds an in-memory tree.

Your choice is therefore not between two different kinds of parser. Your choice is whether to have the parser pass events straight to your application, or to have it pass events to a tree-builder, and then pass the completed tree to your application.

The parser does not use a significant amount of memory. The tree-builder does. But the tree-builder presents the information to the application in a form that is much easier to process.

Do Streaming and Tree-Based XML parsers consume similar amounts of mem...

java xml dom xml-parsing sax
Rectangle 27 2

I would prefer to use jquery for dom manipulation or traversing the dom , which is really easy with jquery . Moreover, attaching an event or event delegation are so easy using jquery or other framework otherwise you have to write custom event attachment for IE or non IE browsers etc.

But it has some performance penalty when you use $.each instead of vanilla JS for and array.push()... other issues like if you bind an event and remove that without unbind it will have memory leak....

My conclusion is only use any framework for complex dom manipulation and rest use vanilla JS

javascript - What are some empirical technical reasons not to use jQue...

javascript jquery frameworks
Rectangle 27 2

I would prefer to use jquery for dom manipulation or traversing the dom , which is really easy with jquery . Moreover, attaching an event or event delegation are so easy using jquery or other framework otherwise you have to write custom event attachment for IE or non IE browsers etc.

But it has some performance penalty when you use $.each instead of vanilla JS for and array.push()... other issues like if you bind an event and remove that without unbind it will have memory leak....

My conclusion is only use any framework for complex dom manipulation and rest use vanilla JS

javascript - What are some empirical technical reasons not to use jQue...

javascript jquery frameworks
Rectangle 27 10

The above answer only deal with DOM parser (that normally reads the entire file in memory and parse it, what for a big file is a problem), you could use a SAX parser that uses less memory and is faster (anyway that depends on your code).

SAX parser callback some functions when it find a start of element, end of element, attribute, text between elements, etc, so it can parse the document and at the same time you get what you need.

java - How to read and write xml files? - Stack Overflow

java xml xml-parsing