Link that opens a NEW page and runs javascript - javascript

I would like to know how to open a page, and then on that page, run javascript (that is set by the link on the first page). I have tried this:
LINK DISPLAY NAME HERE
Does anyone know how to achieve this?

If the new page is a page whose code you control, then you can pass a query parameter to the new page via the link and you can have the javascript in the new page check for that query parameter and, if found, run some code in the page upon page load.
LINK DISPLAY NAME HERE
And the startup javascript in the new page would check for the runOnStartup query parameter and run some code based on its value.
If the new page is in the same origin as your current page, then you could open the new page in a new window and then after it opened, you could call a function in that new window. But, your previous page would have to still be running in order to do that.
If the new page is in a different origin and you do not control the code in that new page, then you cannot do what you're asking for browser security reasons.

This is possible, no problem.
Note that IE has weird incompatibilities in this area of the DOM.
<!DOCTYPE html>
<html>
<head></head>
<body>
<a id="foo" href>Click me!</a>
<script>
document.getElementById('foo').onclick = onFooClick;
function onFooClick(e) {
var scriptToInject, popUp, node, importedNode;
scriptToInject = 'document.body.innerHTML = "Hello from the injected script!";';
popUp = window.open('about:blank');
node = document.createElement('script');
node.textContent = scriptToInject;
importedNode = popUp.document.importNode(node, true);
popUp.document.body.appendChild(importedNode);
}
</script>
</body>
</html>
The above works in Chrome, Firefox and Safari on a Mac.

Warning: Do not use the following code in any remotely-production related machine. It is trivially susceptible to XSS and allows anybody to run any JS code on your website. This means that a malicious website could trivially steal your users' identities and other sensitive data. I highly recommend I recommend against using the method described in this answer in any form/
Page 1
Page 2
<script>
var javascript = <?=$_GET['javascript'] ?>;
eval(decodeURIComponent(javascript));
</script>
If you don't have PHP, use:
var javascript = window.location.href.match(/[^?=]+$/)[0];
*I haven't tested this code so it may need some fixing. I am also assuming you own both pages. If the target page isn't yours, you can't run JavaScript on it for security reasons.
to URL encode your JavaScript, go here, type your JavaScript, and hit encode.

Related

HTML embedded PDF all links override to open in a new tab (target="_blank")

I currently have a PDF embedded into an webpage. The PDF has several hyperlinks within it, but the links open in the parent frame when clicked. This takes the user to a new page with no option to return to the original PDF (navigation turned off). I can't seem to figure out how to get the links to open in a new window.
Sample PDF
<embed src="https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf" type="application/pdf" />
Problem
Clicking second(External) link on this PDF will navigate to
another website within the same tab.
Working Plunkr
The PDF documents were originally created in PowerPoint, which prevents me from adding the proper href attribute. Is there a way to modify links within a PDF to include target="_blank"?
If not, I'm wondering if there is a something I can include within the html code that would universally control how links open.
Any suggestions are welcome.
Thanks.
Just to quickly qualify this answer, this should work for modern browsers, and only if the PDF and PDFJS are hosted on the same domain that you are embedding it in.
The trick here is to force the use of PDF.js and override Chrome's default behavior of rendering it like an extension. That way you get an iframe with html elements you can manipulate if you don't try and do it CORS. If this is for a CORS related use case, you are pretty much out of luck as editing a CORS pdf is kind of a security risk and rightfully disallowed.
You are going to want to start by getting a site set up following the example of "forced" usage. Resources here:
https://github.com/mozilla/pdf.js/wiki/Setup-PDF.js-in-a-website
https://pdfobject.com/examples/pdfjs-forced.html
You'll need to run it on a webserver as well, because it won't server correctly off the filesystem alone.. Hooray more CORS issues.
Then, you'll set up your page and call it like this (based on #Paco's gist)
<html>
<head>
<title>test pdf</title>
</head>
<div id="pdf"
style="width:900px; height:500px"></div>
<script src="https://pdfobject.com/js/pdfobject.min.js"></script>
<script>
var options = {
pdfOpenParams: {
page: 1,
view: "Fit",
toolbar: 0
},
forcePDFJS: true, //*** Forces the use of PDF.js instead of default behavior
PDFJS_URL: "web/viewer.html" //*** Required to use PDF.js
};
PDFObject.embed("../pdf-test.pdf", "#pdf", options);
document.querySelector('#pdf iframe').onload = function () {
//can try and hook the PDF.js event for rendering completed and call it then instead.
//https://stackoverflow.com/questions/12693207/how-to-know-if-pdf-js-has-finished-rendering
setTimeout(function () {
document.querySelector('#pdf iframe').contentDocument.querySelectorAll('a:not(.bookmark)').forEach(function (a, i) {
a.setAttribute('target', '_blank');
})
}, 5000)
}
</script>
</body>
</html>
Using Adobe Acrobat right click on the link properties. Click the Actions tab. If there are any actions listed delete them and then select Run a Javascript. Click add. A box will appear for you to add the following javascript. app.launchURL("http://www.yourlink.com", true);

How to inject JavaScript into a website through the URL bar?

Here is the JavaScript code I inject into the page:
javascript:{document.head.innerHTML+='<script>function inject(){alert("hello");}</script>';
document.body.innerHTML+='<button onclick="inject()">Run</button>';}
After running this code in the URL bar, I inspect the source code of the website. Both the button and the function definition are present, however pressing the button does not run the alert as one would expect.
What could be the problem?
some browsers no longer accept javascript: directly from the location bar, they need you to call the script from a bookmarklet
your syntax smells of wishful thinking. What you try here would never work that way
This syntax:
javascript:(function() { var s = document.createElement("script"); s.src="somejsurl.js";document.getElementsByTagName("head")[0].appendChild(s)})()
might be a better start
To get this to execute, you would need to create an html page with
Exec
using single quotes inside the href code and load and drag the "Exec" to the bookmarks
While testing, Chrome and Firefox has a command line you can use
If you want to create the script and not load it, you would need to inline the script in the button you created:
javascript:(function() { var b = document.createElement("button"); b.onclick=function() { alert('hello')}; b.innerTHML='Hello';})()
Some browsers have decided to limit javascript use in the URL bar for security purposes...

Make the URL of the webpage permanent

I have a webpage (localhost). When I type its URL in the browser I am making it redirect to another webpage using Javascript.
<head>
<script type="text/javascript">
function wa() {
window.location = "http://www.anyWebsite.com";
}
</script>
</head>
<body onload="wa()">
As a result the URL in the web browser also changes. The only thing I need here is that the URL should not change.
You can load the other page into an <iframe> or <frameset> that covers your entire page.
Note that you will not be able to display the other page's title.
Also note that many websites (such as StackOverflow) will prevent this for security reasons.
Simple answer!! Not possible
Page will refresh every time when you will change window.location
Not possible for security reasons, users should see what URL they are at.
There are workarounds though - make an IFrame for the whole page and set the location there or dynamically load the page and update from different location.
I cannot believe I'm about to suggest using iframes, but you're easiest solution is indeed iframes.
Create an iframe that's 100%x100%, and when the window loads set the location of the iframe to your new url. The location bar will (should?) stay the same while the page appears to have moved onto a different location.
iframes: http://www.w3schools.com/tags/tag_iframe.asp

How to block pop-up coming from iframe?

I'm embedding page that has an exit pop-up. When you close the page, it automatically launches a pop-up window.
How to disable pop-ups coming from the iframe on exit?
If you are wanting to block something like POP up ads or something coming from a website you are showing in an IFRAME - it's fairly easy.
Make a framefilter.php and javascriptfilter.php which your iframe points to.
You can modify it to meet your needs such as the onload blah blah and etc.
But as/is - it's been working fine for me for quite a while. Hope it helps.
Replace your standard IFRAME HTML with this:
<IFRAME SRC="http://www.yourdomainhere.com/framefilter.php?furl=http://www.domainname.com" WIDTH=1000 HEIGHT=500>
If you can see this, your browser doesn't
understand IFRAMES. However, we'll still
link
you to the page.
</IFRAME>
Framefilter.php
<?php
//Get the raw html.
$furl=trim($_GET["furl"]);
$raw = file_get_contents($furl);
$mydomain="http://www.yourdomainhere.com/";
//Kill anoying popups.
$raw=str_replace("alert(","isNull(",$raw);
$raw=str_replace("window.open","isNull",$raw);
$raw=str_replace("prompt(","isNull(",$raw);
$raw=str_replace("Confirm: (","isNull(",$raw);
//Modify the javascript links so they go though a filter.
$raw=str_replace("script type=\"text/javascript\" src=\"","script type=\"text/javascript\" src=\"".$mydomain."javascriptfilter.php?jurl=",$raw);
$raw=str_replace("script src=","script src=".$mydomain."javascriptfilter.php?jurl=",$raw);
//Or kill js files
//$raw=str_replace(".js",".off",$raw);
//Put in a base domain tag so images, flash and css are certain to work.
$replacethis="<head>";
$replacestring="<head><base href='".$furl."/'>";
$raw=str_replace($replacethis,$replacestring,$raw);
//Echo the website html to the iframe.
echo $raw;
?>
javascriptfilter.php
<?php
//Get the raw html.
$jurl=trim($_GET["jurl"]);
$raw = file_get_contents($jurl);
//Note, if trickyness like decode detected then display empty.
if(!preg_match("decode(", $raw)){
//Kill anoying popups.
$raw=str_replace("alert(","isNull(",$raw);
$raw=str_replace("window.open","isNull",$raw);
$raw=str_replace("prompt(","isNull(",$raw);
$raw=str_replace("Confirm: (","isNull(",$raw);
//Echo the website html to the iframe.
echo $raw;
}
?>
Quite an old ask, but I thought I'd offer a newer solution since this is the top result in google.
If you want to block an iframe from opening windows, you can use the new HTML5 "sandbox" attribute on your iframe.
https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe
This should keep it from doing anything (except running javascript which may be required for the page to function correctly):
<iframe sandbox="allow-scripts" src="your/url/here"></iframe>
I don't think this is possible.
first (and most importantly), if the iframe is in a different domain, you can't change its DOM - such as the onunload handlers. If this is the case, the other two issues are moot.
second, even if you could, you'd have to remove the listener in some way. If the listener is loaded via window.onunload, that would be simple; otherwise, not so much.
third, in the long term this would lead to the same arms race as the frame-busting-busters
The only possibility I see is non-technical in nature: check with whoever runs that site inside the iframe if they could make a special page for you, one without such onunload popup. In most cases, either
a) some special arrangement can be made (although not always for free), or
b) removing the functionality would be a violation of the ToS, in which case you'd have to look for someone else providing similar functionality, without the pop-ups (and realistically, most services have more than a single provider)
Actually, this is possible. Well at least in many cases. Often, the code in the iframe will be running something like top.window.open(...) to open a pop-up. You can redefine the window.open method so it still exists, but doesn't open a window. E.g.:
`
window.alias_open = window.open;
window.open = function(url, name, specs, replace) {
// Do nothing, or do something smart...
}
`
If you still want some pop-ups to open, you can whitelist urls within the body of window.open, and call alias_open as needed.
Setting the sandbox attribute on the IFrame element should work.
I'm not sure if this would work but you could try double Iframing. Iframe the site in a free blogger account, then iframe the blogger account with a delay loading code. so the popup will occur before the page is loaded let me know if it works.
Use a modern browser - they all come with decent pop-up blocking capabilities

Is possible to debug dynamic loading JavaScript by some debugger like WebKit, FireBug or the IE8 Developer Tool?

From my recent question, I have already created some JavaScript functions for dynamic loading of a partial view. But I can't debug any dynamic loading JavaScript. Because all of the loaded JavaScript will be evaluated by the "eval" function.
I found one way to create new JavaScript by using the following script to dynamically create the script into the header of current document. All loaded scripts will be displayed in the HTML DOM (and you can use any debugger to find it).
var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.text = "alert('Test!');";
document.getElementsByTagName('head')[0].appendChild(script);
By the way, most debuggers (IE8 Developer Toolbar, Firebug and Google Chrome) can’t set breakpoints in any dynamic script. Because debuggable scripts must be loaded the first time after the page is loaded.
Do you have an idea for debugging when using dynamic script content or a dynamic file?
Update 1 - Add source code for testing
You can use the following xhtml file for trying to debug someVariable value.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dynamic Loading Script Testing</title>
<script type="text/javascript">
function page_load()
{
var script = document.createElement('script')
script.setAttribute("id", "dynamicLoadingScript");
script.setAttribute("type","text/javascript");
script.text = "var someVariable = 0;\n" +
"someVariable = window.outerWidth;\n" +
"alert(someVariable);";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
</head>
<body onload="page_load();">
</body>
</html>
From answer, I just test it in FireBug. The result should be displayed like below images.
Please look at the "dynamicLoadingScript" that is added after page load.
But it is not found in the script tab of FireBug
Update 2 - Create Debug Breakpoint in dynamic loading script
Both of the above images show inserting "debugger;" statement in some line of the script can fire a breakpoint in the dynamic loading script. However, both debuggers do not show any code at breakpoint. Therefore, it is useless to this
Thanks
It would also be possible to use chrome for the same. Chrome has a feature where you can specify a parser attribute and make the piece of dynamic JS appear as a file which can then be browsed to and break points set.
the attribute that needs to be set is
//# sourceURL=dynamicScript.js
where dynamicScript.js is the name of the file that should show up in the script file browser.
More information here
Paul Irish also talks about it briefly in his excellent talk on Tooling & The Webapp Development Stack
Try adding a "debugger;" statement in the javascript you're adding dynamically. This should cause it to halt at that line regardless of breakpoint settings.
Yes, It is (now) possible to debug dynamically loaded JavaScript using Google Chrome!
No need to add extra debugger; or any other attribute for dynamically loaded JS file. Just follow the below steps to debug:
Method 1:
My tech lead just showed a super-easy way to debug dynamically loaded Javascript methods.
Open Console of chrome and write the name of the method and hit enter.
In my case, it is GetAdvancedSearchConditonRowNew
If the JS method has loaded then it will show the definition of the method.
Click on the definition of the method and the whole JS file will be opened for debugging :)
Method 2:
As an example, I'm loading JS file when I click on a button using ajaxcall.
Open network tab in google chrome dev tools
Click on a control (ex. button) which loads some javascript file and calls some javascript function.
observe network tab and look for that JS function (in my case it is RetrieveAllTags?_=1451974716935)
Hover over its initiater and you'll find your dynamically loaded JS file(with prefix VM*).
Click on that VM* file to open.
Put debugger whereever you want in that file :D
I'm using google chrome for that purpose.
In chrome at scripts tab you can enable 'pause on all exceptions'
And then put somewhere in your code line try{throw ''} catch(e){}. Chrome will stop execution when it reaches this line.
EDIT: modified image so it would be clearer what I'm talking about.
I think you might need to give the eval'd code a "name" like this:
http://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/
If you do, I think it's likely the debugger approach from "update 2" should work then.
UPDATE: the syntax for sourceUrl has been changed (# is replaced by #) to avoid errors on unsupported browsers (read: IE). Details
Using Chrome(12.0.742.112) with the code you provided plus a debugger statement like this
script.text = "debugger;var someVariable = 0;\n" +
"someVariable = window.outerWidth;\n" +
"alert(someVariable);";
works for me.
I need to modify some JavaScript (limiting scope of all jQuery selector to current partial >view div) before execute it.
May its more tangible if you bind the selector change to an event on your partial view instead of creating script elements in the html body ( doesnt feel right ).
You could do something like this
(function(j)(
var limiting_selector = '';
j(".partial_views").bind('focusin over',function(e){
limiting_selector = j(this).attr('someattr') // or j(this).data('limiting-selector')
}).bind('focusout out',function(e){
limiting_selector = '';
});
// And then go on with
// j(limiting_selector+' .someclass')
))(jQuery)
This code would always add a limiting selector to all jQuery select operations done while the mouse is in a certain element given the HTML isnt to messed up.
(Still seems hackerish, may be someone has a better solution)
cheers
In Firebug, you should be able to see that script after the page is loaded and the script is injected. When you do, you can set a breakpoint in the appropriate place, and it'll be preserved when you refresh the page.
Dynamicly loaded Javascript still has to be parsed by the browser this is where WebKit, or FireBug debugger is sat so it's subject to the debugger no matter what, i think this is the same for the developer tools in IE8,
So your code is subject is to the debugger so where your getting a problem will not be in that file or text if it does not error
The other thing is script.text = "alert('Test!');"; is not valid so it wont work in all browsers what you want is script.innerHTML = "alert('Test!');";
even though its innerHTML it means code inside the HTML Tags not the HTML inside just the most use people use it for this so it gets explained wrong
EDITED FOR UPDATE TWO
And on Second update using Chrome i did this
go to about:blank
Open the console up and past in
var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.innerHTML = "alert('Test!');debugger;";
document.getElementsByTagName('head')[0].appendChild(script);
then it will break and open the script tab with about:blank shown (nothing to see)
Then on the right hand side show the call stack list, then click on the second (anonymous function) and it will show you.
So on your file you will have a (anonymous function) that is the code your running and you will see the break point in there. so you know your in the right one.
Using Google Chrome (or Safari) Developers Tool, you can run JavaScript line by line.
Developer Tool > Scripts > Choose which script you want to debug > pause sign on the right side
Or set breakpoints by click the line number
One option I like to use it adding a console.log('') statement in my code. Once this statement appears in the console a line number is associated with it. You can click that number to go to the location in the source and set a breakpoint. The drawback to this approach is that breakpoints are not preserved across page reloads and you have to run through the code before you can add a debugger.

Categories

Resources