简体   繁体   中英

How can i load a javascript file using a bookmarklet that in turn does not redirect/rewrite the page?

I'm trying to load this remote debugging solution to debug/interact with DOM/js live. The instructions ask you to put a script block and script link into the HEAD of the page to get it all working. That's fine. It's a great tool.

But what if i wanted a bookmarklet-like way of just "inserting" it into any page. I don't see why this can't be done.

This is my bookmarklet:

javascript:(function(){document.body.appendChild(document.createElement('script')).src='http://url-to-js-file.js?x='+(Math.random());})();

And then "url-to-js-file.js" loads the js for iphonedebug :

ipdConfig = {
    baseUrl: '/ipd/', // trailing slash!
    consoleBaseUrl: 'http://192.168.1.25:8170/' // trailing slash!
}

document.body.appendChild(document.createElement('script')).src='http://192.168.1.25/ipd/ipd.js';

console.log('fin.');

Note that the src property there originally was "/ipd/ipd.js" like the instructions suggest. But it will need to be absolute like this if i want to get the debugger working with other sites.

My problem is that this code will dump the first js file (url-to-js-file.js) into the page ok but when the first file tries to insert the other successive files my page appears to redirect. In fact it does not redirect but just get rewritten. Firebug shows the resulting page as no body but just the ipd js files in the HEAD element.

Why does it do this?

Is it because of the bookmarklet behavior that normally redirects to a new page? I don't think so. Because i'm using a closure in the bookmarklet link. And when i comment out the document.body... line of the "url-to-js-file.js" file the page stays where it is. Is it the nesting? Or may it be something in the other ipd js files causing this?

I've tried putting my "url-to-js-file.js" code into a closure but then the global var ipdConfig becomes invisible to the rest of the ipd code which breaks it.

Any ideas?

My best guess is that the ipd.js file is using document.write() somewhere in its code. In which case you need to modify ipd.js so that it doesn't do this.

As I've suspected, ipd.js is written by a javascript newbie:

document.write('<script src="' + ipdConfig.baseUrl + '_ipd.js"></script>');

Modify it to use appendChild(createElement(...)) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM