JavaScript from a Web page to a Safari extension - safari-extension

Can a Web page communicate directly with a Safari extension on JavaScript level?
Ideally, I'd like some way to invoke the JavaScript in the extension's global page, but talking to the injected script will do, too, since that can talk to the global page via messages.
Direct function calling doesn't work. The window object the page and the injected script have are distinct. safari.self is not available to a regular Web page. Is there dispatchMessage in some other DOM object that's visible to the Web page code?

Found one clumsy workaround. The injected script and the page share the document object. The injected script would create an HTML element in the page (an <input type="hidden"> in my case), give it an agreed-upon ID, and hook its onclick. The page would find that element by ID and invoke onclick, passing some arguments along. The injected script gets control. For script-to-page callbacks, I'd use onchange on the same element.
The calls are synchronous, even.
The injected script would then pass the message on to the extension's global page using safari.self.tab.dispatchMessage().

Related

'Global' parent selector: limiting scope of any selector to a certain parent

Im looking for an option to limit the scope of every selector to a parent selector.
Am trying to abstract away a lot of the (internal implementation) details of our WebApp for the testers that will actually write the UI tests.
If our application shows a Modal dialog (just a div tag that lies op top of all the other content and prevents interacting with the underlying content), I'd like to restrict all Selectors used in the tests written by testers to be automatically limited to the scope of this Modal Dialog div.
Our new client UI framework uses just divs for Modal Dialogs, while our previous client UI framework used an embedded iframe for each modal dialog. In the iframe scenario, we'd call .switchToIframe(), which would effectively limited all selectors used in tests to this iframe.
Am trying to achieve something similar for the new client framework that uses just divs
I'm not sure you can limit the scope of the DOM like that, but you could build out a Page Object Model (POM) design that would only intelliSense existing locators from their respected repos. This way, if they begin typing a locator and it doesn't pop up, a hint that they aren't in the 'scope' of the modal.

Blazor Server, Conditional Elements + JS Invoking

I have a Blazor Server app that is a multi-step "wizard" form. After each relevant step the state is adjusted, and new HTML is shown/hidden via conditional statements (simple example below).
if (IsStepSignature)
{
<div>Signature HTML here</div>
}
This all works just fine. My problem comes when I need to invoke some JS logic on the dynamically generated HTML from above (e.g. click handlers to hook up external JS libraries). When I handle the "Next" click, I can invoke the JS just fine...but it is not yet seeing the dynamic HTML from above. Is there a way to invoke some JS, and control it so that it doesn't execute until after the page is redrawn from the C# code execution?
5/18/2020 Update from Nik P
Can leverage some flags and use OnAfterRenderAsync to control this ordering. This does work, but it does require some extra hops to/from the server. Below is what I see when implementing this. This may just be the nature of Blazor Server, as one of the pros/cons is some known added chattiness. In total these requests were 2.5K, so extremely small.
CLIENT --> Browser Dispatch Event (NEXT CLICK)
Render <-- SERVER
CLIENT --> Render Complete
Invoke JS <-- SERVER
CLIENT --> Invoke Complete
The issue you are having has to do with the element not existing in the client side HTML at all until after the re-render takes place. So one way to do this is to set a boolean flag in your C# code that says there is code that needs to be run after the render, and populate support fields that you will need for your JS Interop. Whenever you need to run the JS interop, set your flag to true, set your support fields to the values you need for the JS interop call, and then do something that kicks a DOM diff calculation. (Even StateHasChanged should be enough, but adding your items conditionally as you mentioned will also do it) Then, override your OnAfterRenderAsync method as follows:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if(firstRender)
{
// any first render code
}
if(yourFlag)
{
YourJSInteropMethod(supportField1, supportfield2);
yourflag = false;
}
}
The simplicity in this approach is that the DOM update will always happen ahead of the OnAfterRenderAsync call, so your HTML will be populated with what you are targeting with JS.

How can I embed a twitter timeline in a Durandal view?

The code to embed the widget is nice and simple, but it includes javascript in tags.
Durandal appears to strip out such script tags.
How do I use the embed code in a Durandal view?
https://dev.twitter.com/web/embedded-timelines
<a class="twitter-timeline" href="https://twitter.com/XXX" data-widget-id="XXX">Tweets by #XXX</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
You would need to write a custom Knockout binding, or create a Durandal widget where the view is your tag, and the viewModel handles the JavaScript in your tag.
Some notes: In your widget's view model, you would avoid d.getElementsByTagName(s) in favor of simply referencing the view reference passed in to either the attached or compositionComplete handler that Durandal provides. In fact, you could pretty much eschew all direct DOM manipulation in favor of Durandal's imported view references and Knockout's/Durandal's templating/composition.
UPDATE
Take a look at this from the documentation you reference: "If you’re already including our ‘widgets.js’ JavaScript in your page to show embedded Tweets or Twitter buttons, you don’t need to include this script again; it updates automatically to support new features."
This could lead you down the path of simply referencing widgets.js in a script tag in your index.html or index.chtml file.
You cannot use script tags in Durandal views, but you can use them in your index page.
SECOND UPDATE
Once widget.js has been referenced in a script tag in the index.html or index.chtml (or perhaps even by using AMD), it becomes a matter of choosing the proper Durandal point at which to load the Twitter widget. This could be either in the attached handler or in the compositionComplete handler, as indicated above.
As the OP pointed out in his comments, a functional place to do this is compositionComplete, in the following manner:
var compositionComplete = function () {
twttr.widgets.load();
}
as documented here.
This assumes that twttr is either on the window or injected into the viewModel.
POSSIBLE MEMORY LEAK
It is equally important to note that unloading of widgets must take place in the Durandal's detached handler. Use Twitter's API to unload, and then be sure to nullify the windows reference.

How to handle many bootstrap modals on a single html page

I would have 10 bootstrap buttons on a single html page.
Each button opens a ootstrap modal filled with a html fragmen via an ajax request.
<div class="modal fade" id="myModal"></div>
$('#myModal').modal();
Should I create 10 different divs with 10 different ids? Or even 10 different instances?
var dialogInstance1 = new BootstrapDialog({
title: 'Dialog instance 1',
message: 'Hi Apple!'
});
or
should I create ONE dialog?
I would expect kind of caching problems when I open modal1, then just when I open modal2 I see still for some miliseconds modal1 html fragment from a prvious ajax request.
And how should I create those modals? The samples should this:
$('#myModal').modal();
and the instantiation? This is very confusing.
Can someone please share his experience how to approach with many bootstrap modals?
I would expect kind of caching problems when I open modal1, then just when I open modal2 I see still for some miliseconds modal1 html fragment from a prvious ajax request.
Assuming you're referring to data-remote's caching, you will probably be able to disable that in Bootstrap v3.2.0 (see https://github.com/twbs/bootstrap/pull/13183/ ).
However, I'd still recommend against using data-remote since it doesn't give you much control. It:
doesn't provide or easily let you do any error handling
doesn't give any "loading..." indication
forces you have to generate modal HTML on the server side (as opposed to, e.g., returning JSON from the server and using client-side templating)
IMO, you should:
include just one instance of the blank modal markup
setup your own click event handlers on the buttons that summon your modal
initiate the AJAX request in your click event handler
use client-side templating to generate a corresponding modal using the results of the request
use $(...).modal() or $(...).modal('show') (depends on how your templating works) to show the modal after the templating completes

WP8 WebBrowser: inline script works, loaded doesn't

Windows Phone 8 app, WebBrowser control. I load a chunk of HTML via NavigateToString (after setting IsScriptEnabled=true). Some time later (long after it's loaded), I'm invoking some JavaScript on the page with InvokeScript.
When I invoke a JavaScript function that's defined inline inside a <script> element, it works as expected. When I invoke one that's defined in an external JS file, it doesn't, and an exception from HRESULT 0x80020006 ("name not found") is thrown.
The external script file is loaded from my app package. In the HTML string, there's a <base> element which contains a file:// URL to the package's folder (retrieved via Package::Current->InstalledLocation), and the <script> element contains just the file name. There are also styles and images in that folder - they load fine.
The HTML has no DOCTYPE and no xmlns - I know those things can sometimes throw JavaScript off.
The external script file is valid - it came straight from Android where it worked on the respective WebView control. The function I'm trying to invoke is empty anyway, to be on the safe side, JavaScript syntax-wise.
This could in theory be some kind of a cross-domain scripting issue. Technically, the script comes from a file:// URL while the page itself comes from no URL at all. Some piece of system code that makes sure no fishy script is called could've gotten in the way.
Found one workaround: load the external script file into a string on startup, once the HTML is loaded (LoadCompleted fires), feed it to the document using JavaScript eval.
Here is example of how to inject some script dynamically
Browser.InvokeScript("eval", new string[] { FileUtils.ReadFileContent("app/www/js/console.js") });
Where ReadFileContent could be defined as following
https://github.com/sgrebnov/IeMobileDebugger/blob/master/Libraries/Support/FileUtils.cs
Full example
https://github.com/sgrebnov/IeMobileDebugger/blob/master/Libraries/IE.Debug.Core/WebPageDebugger.cs
PS. instead of reading script from file you can pass hardcoded string, etc
Are you sure that your script is being loaded? One thing you can do is tuck an alert in there to make sure it is being loaded. My suspicion is that it isn't being loaded.
Any time I have run into this before that has been the case although admittedly I haven't loaded a JS file from Isolated Storage before.