Vandervals
Vandervals

Reputation: 6054

How to test a script in multiple sites just by using chrome dev-tools?

First of all I'm not quite sure this is the place for this kind of question, if not please tell me and I'll remove it.

I'm developing a script that modifies the DOM a bit and I'd like to test it in real sites to see if it behaves correctly and to detect issues.

I was wondering how simulate that the script is at that page and if it would be possible by using chrome dev-tools.

At first I tried adding the script to the but the script doesn't execute.

I tried writing this on the console but didn't work:

var script1 = document.createElement("script");
var script2 = document.createElement("script");
var head = document.querySelector("head");
var text = 'myscript();';
script2[(script2.innerText===undefined?"textContent":"innerText")] = text;

script1.setAttribute("src", "http://mysite.myscript.js");
head.appendChild(script1);
script1.onload = function(){ head.appendChild(script2) };

EDIT: Actually that script worked but in the inside I was listening to a DOMcontentLoad event, so of course when I executed that from the console, the dom was already loaded.

Upvotes: 0

Views: 108

Answers (1)

Garbee
Garbee

Reputation: 10981

This can be done using the DevTools. To make it easy to do in many places, you should take advantage of a feature called Snippets.

This is the code I used to test in my snippet. I changed the "mysite" URL to pull a copy of Material Design Lite's JS and set the text to log the componentHandler object. Other than these changes, it is your code:

var script1 = document.createElement("script");
var script2 = document.createElement("script");
var head = document.querySelector("head");
var text = 'console.log(componentHandler);';
script2[(script2.innerText===undefined?"textContent":"innerText")] = text;

script1.setAttribute("src", "https://storage.googleapis.com/code.getmdl.io/1.0.0/material.min.js");
head.appendChild(script1);
script1.onload = function(){ head.appendChild(script2) };

With this you need to do the following steps:

  1. Open the sources panel
  2. Go to the "Snippets" resources tab in the left hand panel (green arrow.)
  3. Right click in the resource views (blue) and select "New Snippet"
  4. Name the snippet, in my case I used "test" for the name. Just make sure you understand what it is.
  5. Fill in content editor with script.
  6. Once content is saved, right click on the script in the resources listing. Then select "Run Snippet"
  7. Check console (Red outline, for drawer or you may go to the console panel itself) to see output.

Snippet Usage

To verify further that this is working, you can go check the Elements Panel.

injected data

Upvotes: 1

Related Questions